CTF杂项做题脚本

5 篇文章 4 订阅

base64批量解密

import base64
path = input("Path : ")#填写文件路径即可文件为txt格式
address = (path[0:(len(path) - len(path.split('\\')[-1]))])
with open(path,'rb') as file:
    with open(address+'b64decode_'+path.split('\\')[-1],'wb') as new_file:
        for i in file.readlines():
            new_file.write(base64.b64decode(i))

base64隐写

import base64

b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

path = input("Path : ")
address = (path[0:(len(path) - len(path.split('\\')[-1]))])
with open(path, 'rb') as f:
    flag = ''
    bin_str = ''
    for line in f.readlines():
        stegb64 = str(line, "utf-8").strip("\n")
        rowb64 = str(base64.b64encode(base64.b64decode(stegb64)), "utf-8").strip("\n")
        offset = abs(b64chars.index(stegb64.replace('=', '')[-1]) - b64chars.index(rowb64.replace('=', '')[-1]))
        equalnum = stegb64.count('=')  # no equalnum no offset
        if equalnum:
            bin_str += bin(offset)[2:].zfill(equalnum * 2)
            # flag += chr(int(bin(offset)[2:].zfill(equalnum * 2), 2))
            # print(flag) 这样写得不出正确结果
            #print(([chr(int(bin_str[i:i + 8], 2)) for i in range(0, len(bin_str), 8)]))
    flag = ([chr(int(bin_str[i:i + 8], 2)) for i in range(0, len(bin_str), 8)])
with open(address+'steg_'+path.split('\\')[-1],'w') as file:
    for i in flag:
        file.write(i)

from urllib3.connectionpool import xrange


def get_base64_diff_value(s1, s2):
    base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    res = 0
    for i in xrange(len(s2)):
        if s1[i] != s2[i]:
            return abs(base64chars.index(s1[i]) - base64chars.index(s2[i]))
    return res


def solve_stego():
    with open('flag.txt', 'rb') as f:
        file_lines = f.readlines()
        bin_str = ''
        for line in file_lines:
            steg_line = line.replace('\n', '')
            norm_line = line.replace('\n', '').decode('base64').encode('base64').replace('\n', '')
            diff = get_base64_diff_value(steg_line, norm_line)
            print diff
            pads_num = steg_line.count('=')
            if diff:
                bin_str += bin(diff)[2:].zfill(pads_num * 2)
            else:
                bin_str += '0' * pads_num * 2
            print goflag(bin_str)


def goflag(bin_str):
    res_str = ''
    for i in xrange(0, len(bin_str), 8):
        res_str += chr(int(bin_str[i:i + 8], 2))
    return res_str


if __name__ == '__main__':
    solve_stego()

PNG高宽CRC修复脚本

import binascii
import struct
import sys

file = input("图片地址:")
fr = open(file,'rb').read()
data = bytearray(fr[0x0c:0x1d])
crc32key = eval('0x'+str(binascii.b2a_hex(fr[0x1d:0x21]))[2:-1])
#原来的代码: crc32key = eval(str(fr[29:33]).replace('\\x','').replace("b'",'0x').replace("'",''))
n = 4095
for w in range(n):
    width = bytearray(struct.pack('>i', w))
    for h in range(n):
        height = bytearray(struct.pack('>i', h))
        for x in range(4):
            data[x+4] = width[x]
            data[x+8] = height[x]
        crc32result = binascii.crc32(data) & 0xffffffff
        if crc32result == crc32key:
            print(width,height)
            newpic = bytearray(fr)
            for x in range(4):
                newpic[x+16] = width[x]
                newpic[x+20] = height[x]
            fw = open(file+'.png','wb')
            fw.write(newpic)
            fw.close
            sys.exit()

PNG爆破高宽非CRC

import zlib
import struct
filename = input("file:")
with open(filename, 'rb') as f:
    all_b = f.read()
    #w = all_b[16:20]
    #h = all_b[20:24]
    for i in range(901,1200):
        name = str(i) + ".png"
        f1 = open(r"./output/" + name,"wb")
        im = all_b[:16]+struct.pack('>i',i)+all_b[20:]
        f1.write(im)
        f1.close()

JPG爆破非CRC

import zlib
import struct
filename = input("file:")
with open(filename, 'rb') as f:
    all_b = f.read()
    #w = all_b[159:161]
    #h = all_b[157:159]
    for i in range(901,1200):
        name = str(i) + ".jpg"
        f1 = open(r"./output/" + name,"wb")
        im = all_b[:159]+struct.pack('>h',i)+all_b[161:]
        f1.write(im)
        f1.close()

BMP爆破高度脚步

import struct
import zlib
import os
os.system("mkdir bpout")

file_path = input("Path : ")
f = open(file_path,'rb')
c = f.read()
width = c[18:22]
height = c[22:26]
# 爆破bmp宽度
for i in range(900,1100):
    f1 = open('./bpout/'+str(i)+'.bmp','wb')
    # print(struct.pack('>i',i)[::-1])
    img = c[:18]+struct.pack('>i',i)[::-1]+c[22:]
    f1.write(img)
    f1.close()

LSB隐写脚本

#!/usr/bin/env python
# coding:UTF-8
"""LSBSteg.py

Usage:
  LSBSteg.py encode -i <input> -o <output> -f <file>
  LSBSteg.py decode -i <input> -o <output>

Options:
  -h, --help                Show this help
  --version                 Show the version
  -f,--file=<file>          File to hide
  -i,--in=<input>           Input image (carrier)
  -o,--out=<output>         Output image (or extracted file)
"""

import cv2
import docopt
import numpy as np


class SteganographyException(Exception):
    pass


class LSBSteg():
    def __init__(self, im):
        self.image = im
        self.height, self.width, self.nbchannels = im.shape
        self.size = self.width * self.height
        
        self.maskONEValues = [1,2,4,8,16,32,64,128]
        #Mask used to put one ex:1->00000001, 2->00000010 .. associated with OR bitwise
        self.maskONE = self.maskONEValues.pop(0) #Will be used to do bitwise operations
        
        self.maskZEROValues = [254,253,251,247,239,223,191,127]
        #Mak used to put zero ex:254->11111110, 253->11111101 .. associated with AND bitwise
        self.maskZERO = self.maskZEROValues.pop(0)
        
        self.curwidth = 0  # Current width position
        self.curheight = 0 # Current height position
        self.curchan = 0   # Current channel position

    def put_binary_value(self, bits): #Put the bits in the image
        for c in bits:
            val = list(self.image[self.curheight,self.curwidth]) #Get the pixel value as a list
            if int(c) == 1:
                val[self.curchan] = int(val[self.curchan]) | self.maskONE #OR with maskONE
            else:
                val[self.curchan] = int(val[self.curchan]) & self.maskZERO #AND with maskZERO
                
            self.image[self.curheight,self.curwidth] = tuple(val)
            self.next_slot() #Move "cursor" to the next space
        
    def next_slot(self):#Move to the next slot were information can be taken or put
        if self.curchan == self.nbchannels-1: #Next Space is the following channel
            self.curchan = 0
            if self.curwidth == self.width-1: #Or the first channel of the next pixel of the same line
                self.curwidth = 0
                if self.curheight == self.height-1:#Or the first channel of the first pixel of the next line
                    self.curheight = 0
                    if self.maskONE == 128: #Mask 1000000, so the last mask
                        raise SteganographyException("No available slot remaining (image filled)")
                    else: #Or instead of using the first bit start using the second and so on..
                        self.maskONE = self.maskONEValues.pop(0)
                        self.maskZERO = self.maskZEROValues.pop(0)
                else:
                    self.curheight +=1
            else:
                self.curwidth +=1
        else:
            self.curchan +=1

    def read_bit(self): #Read a single bit int the image
        val = self.image[self.curheight,self.curwidth][self.curchan]
        val = int(val) & self.maskONE
        self.next_slot()
        if val > 0:
            return "1"
        else:
            return "0"
    
    def read_byte(self):
        return self.read_bits(8)
    
    def read_bits(self, nb): #Read the given number of bits
        bits = ""
        for i in range(nb):
            bits += self.read_bit()
        return bits

    def byteValue(self, val):
        return self.binary_value(val, 8)
        
    def binary_value(self, val, bitsize): #Return the binary value of an int as a byte
        binval = bin(val)[2:]
        if len(binval) > bitsize:
            raise SteganographyException("binary value larger than the expected size")
        while len(binval) < bitsize:
            binval = "0"+binval
        return binval

    def encode_text(self, txt):
        l = len(txt)
        binl = self.binary_value(l, 16) #Length coded on 2 bytes so the text size can be up to 65536 bytes long
        self.put_binary_value(binl) #Put text length coded on 4 bytes
        for char in txt: #And put all the chars
            c = ord(char)
            self.put_binary_value(self.byteValue(c))
        return self.image
       
    def decode_text(self):
        ls = self.read_bits(16) #Read the text size in bytes
        l = int(ls,2)
        i = 0
        unhideTxt = ""
        while i < l: #Read all bytes of the text
            tmp = self.read_byte() #So one byte
            i += 1
            unhideTxt += chr(int(tmp,2)) #Every chars concatenated to str
        return unhideTxt

    def encode_image(self, imtohide):
        w = imtohide.width
        h = imtohide.height
        if self.width*self.height*self.nbchannels < w*h*imtohide.channels:
            raise SteganographyException("Carrier image not big enough to hold all the datas to steganography")
        binw = self.binary_value(w, 16) #Width coded on to byte so width up to 65536
        binh = self.binary_value(h, 16)
        self.put_binary_value(binw) #Put width
        self.put_binary_value(binh) #Put height
        for h in range(imtohide.height): #Iterate the hole image to put every pixel values
            for w in range(imtohide.width):
                for chan in range(imtohide.channels):
                    val = imtohide[h,w][chan]
                    self.put_binary_value(self.byteValue(int(val)))
        return self.image

                    
    def decode_image(self):
        width = int(self.read_bits(16),2) #Read 16bits and convert it in int
        height = int(self.read_bits(16),2)
        unhideimg = np.zeros((width,height, 3), np.uint8) #Create an image in which we will put all the pixels read
        for h in range(height):
            for w in range(width):
                for chan in range(unhideimg.channels):
                    val = list(unhideimg[h,w])
                    val[chan] = int(self.read_byte(),2) #Read the value
                    unhideimg[h,w] = tuple(val)
        return unhideimg
    
    def encode_binary(self, data):
        l = len(data)
        if self.width*self.height*self.nbchannels < l+64:
            raise SteganographyException("Carrier image not big enough to hold all the datas to steganography")
        self.put_binary_value(self.binary_value(l, 64))
        for byte in data:
            byte = byte if isinstance(byte, int) else ord(byte) # Compat py2/py3
            self.put_binary_value(self.byteValue(byte))
        return self.image

    def decode_binary(self):
        l = int(self.read_bits(64), 2)
        output = b""
        for i in range(l):
            output += bytearray([int(self.read_byte(),2)])
        return output


def main():
    args = docopt.docopt(__doc__, version="0.2")
    in_f = args["--in"]
    out_f = args["--out"]
    in_img = cv2.imread(in_f)
    steg = LSBSteg(in_img)
    lossy_formats = ["jpeg", "jpg"]

    if args['encode']:
        #Handling lossy format
        out_f, out_ext = out_f.split(".")
        if out_ext in lossy_formats:
            out_f = out_f + ".png"
            print("Output file changed to ", out_f)

        data = open(args["--file"], "rb").read()
        res = steg.encode_binary(data)
        cv2.imwrite(out_f, res)

    elif args["decode"]:
        raw = steg.decode_binary()
        with open(out_f, "wb") as f:
            f.write(raw)


if __name__=="__main__":
    main()


RGB数据转图片

from PIL import Image
path = input('path:')

x = int(input('x:'))
y = int(input('y:'))

img = Image.new('RGB', (x,y))
file = open(path,'r')
for width in range(0,x):
    for height in range(0,y):
        line = file.readline().replace('\n','').replace('(','').replace(')','')
        print(line)
        rgb = line.split(',')
        print(rgb)
        img.putpixel((width,height), (int(rgb[0]), int(rgb[1]), int(rgb[2])))
img.save('flag.png')

递归解压压缩包

针对的是Windows下密码是上个压缩包的密码的那种,如果要以当前压缩包名字为密码,请把passwd = ss

import zipfile

file_path = input('path : ')#压缩包路径
path = file_path[0:len(file_path)-len(file_path.split('\\')[-1])]
n = 0
s2 = ""

def extract():
    i = file_path.split('\\')[-1]#递归解压压缩包名称


    str1 = ''
    for x in range(1000):
        ss = i[:i.find(".")]

        zpf = zipfile.ZipFile(path + ss + ".zip")
        list = zpf.namelist()
        #print(list)
        print(x + 1)
        for f in list:

            #print(f)

            passwd = f.split('.')[0]#压缩包密码

            zpf.extract(f, path, bytes(passwd.encode('utf-8')))
            if 'zip' in f:
                print(path, passwd)
                i = str(f)


extract()


Linux下解压密码是当前压缩包名称

import zipfile

file_path = input('path : ')#压缩包路径
path = "/Users/mzq/Desktop/ctf/buuctf/misc/[MRCTF2020]千层套路/"
# path = file_path[0:len(file_path)-len(file_path.split('//')[-1])]
print(path)
n = 0
s2 = ""

def extract():
    i = file_path.split('\\')[-1]#递归解压压缩包名称
    print(i)


    str1 = ''
    for x in range(1000):
        ss = i[:i.find(".")]
        print(ss)

        zpf = zipfile.ZipFile( path+ss + ".zip")
        list = zpf.namelist()
        #print(list)
        print(x + 1)
        for f in list:

            #print(f)
            passwd = ss
            #passwd = f.split('.')[0]#压缩包密码
            #print(passwd)
            zpf.extract(f, path, bytes(passwd.encode('utf-8')))
            if 'zip' in f:
                print(path, passwd)
                i = str(f)


extract()




读取文件16进制转字符串

import binascii
path = input("Path : ")
address = (path[0:(len(path) - len(path.split('\\')[-1]))])
with open(path,'r') as file:
    with open(address+'new_'+path.split('\\')[-1],'wb') as data:
        for i in file.readlines():
            data.write(binascii.unhexlify(i[:-1]))

数据去重脚本

path = input("Path : ")
with open(path, 'r') as file:
    res_list = []
    lines = file.readlines()
    print('[+]去重之前一共{0}行'.format(len(lines)))
    print('[+]开始去重,请稍等.....')
    for i in lines:
        if i not in res_list:
            res_list.append(i)
    print('[+]去重后一共{0}行'.format(len(res_list)))
    #print(res_list)

address = (path[0:(len(path) - len(path.split('\\')[-1]))])
with open(address+'new_'+path.split('\\')[-1], 'w') as new_file:
    for j in res_list:
        new_file.write(j)

统计字符串

# -*- coding:utf-8 -*-
#Author: mochu7
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+- =\\{\\}[]"
file_path = input('please input path:')
strings = open(file_path).read()

result = {}
for i in alphabet:
	counts = strings.count(i)
	i = '{0}'.format(i)
	result[i] = counts

res = sorted(result.items(),key=lambda item:item[1],reverse=True)
for data in res:
	print(data)

for i in res:
	flag = str(i[0])
	print(flag[0],end="")

线性回归求AB

import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize as op
import math
a=[[(376, 38462.085), (485, 49579.895), (28, 2964.377), (390, 39888.567), (222, 22753.108), (388, 39685.235), (24, 2556.346), (204, 20916.088), (45, 4698.592), (9, 1026.251), (428, 43765.177), (334, 34176.356), (205, 21018.683), (218, 22344.21), (69, 7146.245), (347, 35503.166), (479, 48967.208), (213, 21834.244), (227, 23262.95), (460, 47029.989), (118, 12144.819), (491, 50192.035), (44, 4596.27), (241, 24690.668), (476, 48661.456), (18, 1944.416), (427, 43664.197), (214, 21936.838), (274, 28056.588), (272, 27853.2)]

,[(85, 8348.621), (346, 33665.322), (101, 9900.75), (286, 27845.358), (490, 47634.336), (256, 24935.159), (499, 48507.783), (384, 37352.466), (314, 30561.655), (47, 4662.515), (279, 27166.774), (449, 43656.702), (415, 40358.941), (335, 32598.173), (445, 43269.738), (257, 25033.479), (56, 5535.53), (484, 47053.0), (24, 2431.123), (447, 43463.332), (252, 24547.35), (269, 26197.073), (375, 36478.885), (467, 45404.153), (299, 29106.661), (410, 39874.781), (111, 10870.232), (162, 15817.212), (473, 45985.348), (428, 41620.527)]

,[(482, 59363.599), (493, 60717.612), (242, 29842.836), (403, 49645.494), (257, 31687.884), (418, 51490.659), (382, 47062.795), (172, 21232.594), (409, 50383.537), (37, 4627.411), (113, 13975.622), (283, 34886.502), (62, 7702.363), (438, 53951.295), (95, 11761.148), (164, 20248.214), (270, 33287.123), (60, 7456.365), (89, 11023.68), (165, 20371.405), (222, 27382.086), (416, 51244.099), (433, 53335.646), (422, 51983.683), (29, 3643.292), (466, 57395.086), (109, 13483.208), (200, 24677.075), (371, 45710.712), (325, 40052.51)]

,[(214, 10596.501), (338, 16672.817), (383, 18878.996), (198, 9813.117), (149, 7411.18), (439, 21621.139), (12, 698.274), (30, 1580.109), (425, 20935.333), (372, 18338.869), (52, 2658.353), (282, 13928.514), (421, 20740.908), (242, 11968.381), (223, 11037.519), (46, 2364.361), (314, 15497.448), (225, 11135.62), (210, 10400.927), (168, 8342.544), (104, 5206.607), (175, 8685.26), (437, 21523.478), (55, 2805.311), (419, 20642.936), (79, 3981.11), (473, 23287.359), (207, 10253.953), (379, 18682.114), (498, 24512.699)]

,[(444, 22697.484), (201, 10303.965), (442, 22594.985), (268, 13720.463), (215, 11018.358), (64, 3316.136), (99, 5101.527), (117, 6019.476), (42, 2194.3), (235, 12037.331), (447, 22850.954), (491, 25093.206), (400, 20452.699), (409, 20911.527), (303, 15505.555), (430, 21983.053), (166, 8518.432), (91, 4693.31), (197, 10099.772), (147, 7549.539), (115, 5917.528), (390, 19942.57), (396, 20250.15), (386, 19739.285), (144, 7396.758), (185, 9488.074), (308, 15761.079), (299, 15301.183), (453, 23156.869), (326, 16678.433)]

,[(157, 17994.029), (466, 53219.713), (298, 34067.876), (336, 38400.176), (404, 46152.114), (35, 4085.249), (370, 42277.13), (74, 8531.099), (38, 4427.459), (356, 40680.902), (461, 52649.548), (103, 11837.351), (287, 32814.011), (153, 17537.147), (105, 12065.227), (165, 18905.831), (383, 43758.064), (14, 1691.277), (149, 17081.899), (48, 5567.135), (60, 6935.317), (183, 20958.053), (425, 48546.553), (124, 14231.309), (154, 17651.315), (305, 34865.077), (225, 25745.798), (22, 2603.436), (260, 29735.779), (268, 30648.491)]

,[(35, 2921.193), (74, 6119.615), (366, 30063.851), (84, 6939.611), (445, 36541.644), (266, 21864.537), (44, 3659.23), (21, 1773.203), (281, 23094.394), (446, 36625.1), (134, 11039.599), (224, 18419.597), (125, 10301.272), (187, 15386.092), (27, 2265.144), (384, 31540.715), (312, 25636.875), (81, 6693.404), (256, 21043.915), (272, 22355.386), (413, 33917.33), (466, 38263.262), (10, 871.15), (322, 26455.254), (491, 40314.018), (285, 23422.235), (299, 24569.304), (314, 25799.903), (472, 38756.921), (207, 17025.119)]

,[(18, 1909.09), (423, 43626.197), (443, 45686.428), (434, 44759.148), (227, 23436.716), (129, 13342.914), (6, 673.051), (30, 3145.382), (182, 18801.909), (53, 5514.395), (38, 3969.362), (306, 31573.971), (449, 46303.27), (342, 35281.657), (208, 21479.106), (58, 6029.494), (426, 43933.203), (31, 3248.286), (455, 46921.265), (46, 4793.37), (67, 6956.534), (436, 44964.671), (352, 36311.115), (39, 4072.332), (482, 49703.378), (36, 3763.208), (490, 50525.775), (404, 41667.513), (411, 42389.72), (87, 9016.124)]

,[(466, 47119.357), (238, 24091.99), (378, 38231.425), (397, 40151.664), (62, 6315.361), (16, 1669.443), (495, 50048.255), (248, 25101.314), (97, 9850.418), (496, 50149.486), (250, 25303.773), (254, 25708.162), (151, 15304.476), (298, 30151.49), (39, 3992.359), (301, 30455.131), (487, 49240.674), (137, 13890.614), (170, 17223.704), (12, 1265.129), (306, 30959.984), (324, 32777.275), (354, 35808.118), (259, 26213.599), (61, 6214.064), (315, 31869.574), (419, 42373.779), (36, 3689.172), (56, 5709.441), (347, 35101.57)]

,[(128, 10673.706), (410, 34080.113), (400, 33250.109), (495, 41134.303), (102, 8515.216), (388, 32253.575), (421, 34992.384), (126, 10507.612), (448, 37233.402), (230, 19139.667), (432, 35905.656), (343, 28519.819), (224, 18641.439), (16, 1377.078), (70, 5859.254), (188, 15653.68), (41, 3452.216), (262, 21795.981), (452, 37565.629), (496, 41218.974), (48, 4033.309), (19, 1626.453), (179, 14906.658), (490, 40720.602), (293, 24368.848), (17, 1460.317), (315, 26195.299), (351, 29182.612), (219, 18226.844), (192, 15985.401)]

,[(366, 17679.993), (311, 15039.672), (144, 7022.587), (56, 2798.177), (40, 2030.32), (86, 4238.677), (393, 18974.814), (409, 19742.828), (266, 12878.464), (53, 2654.169), (356, 17199.18), (233, 11294.64), (70, 3470.511), (89, 4382.363), (80, 3950.705), (378, 18255.237), (139, 6782.707), (120, 5870.596), (31, 1598.134), (492, 23728.638), (453, 21856.637), (210, 10190.151), (47, 2366.403), (306, 14798.785), (235, 11390.721), (22, 1166.112), (471, 22719.415), (108, 5294.502), (413, 19936.025), (329, 15903.103)]

,[(400, 38065.613), (406, 38635.921), (426, 40536.452), (228, 21725.303), (484, 46046.395), (297, 28280.548), (176, 16786.046), (316, 30085.821), (35, 3390.384), (315, 29990.94), (421, 40060.658), (448, 42627.029), (396, 37685.191), (458, 43575.818), (366, 34836.594), (474, 45095.324), (476, 45287.017), (36, 3485.245), (473, 45000.45), (22, 2155.411), (409, 38920.804), (362, 34455.627), (196, 18685.953), (450, 42816.42), (86, 8235.263), (266, 25335.452), (427, 40631.459), (423, 40252.254), (115, 10990.549), (180, 17165.868)]

,[(399, 37977.029), (141, 13467.056), (491, 46716.435), (236, 22491.873), (415, 39497.438), (239, 22776.126), (378, 35981.953), (404, 38452.185), (20, 1971.333), (392, 37312.171), (348, 33131.705), (68, 6531.521), (116, 11091.687), (24, 2351.378), (377, 35886.753), (352, 33511.265), (186, 17741.408), (64, 6151.27), (238, 22681.308), (156, 14891.645), (77, 7386.51), (264, 25151.192), (311, 29616.833), (481, 45766.877), (229, 21826.112), (124, 11851.454), (204, 19452.046), (74, 7101.408), (101, 9666.573), (23, 2256.442)]

,[(462, 22255.567), (404, 19472.985), (148, 7183.731), (116, 5647.385), (54, 2671.354), (129, 6271.643), (396, 19089.092), (104, 5071.365), (351, 16928.509), (263, 12704.488), (231, 11167.616), (203, 9824.242), (433, 20865.24), (380, 18319.847), (19, 991.333), (170, 8239.438), (61, 3007.183), (77, 3775.341), (193, 9343.796), (160, 7759.819), (113, 5503.85), (459, 22113.195), (472, 22735.985), (497, 23937.354), (121, 5887.589), (346, 16687.957), (332, 16016.091), (461, 22207.374), (145, 7039.67), (101, 4927.526)]

,[(356, 35695.781), (323, 32396.312), (99, 9995.636), (274, 27495.776), (284, 28495.424), (37, 3795.292), (114, 11495.772), (381, 38195.254), (415, 41595.773), (45, 4595.278), (205, 20596.234), (418, 41896.749), (282, 28296.166), (228, 22896.214), (338, 33896.127), (84, 8495.355), (237, 23795.222), (414, 41495.335), (247, 24795.385), (133, 13395.59), (177, 17795.921), (481, 48195.587), (399, 39995.328), (435, 43595.973), (476, 47696.302), (347, 34797.091), (75, 7595.72), (224, 22495.502), (402, 40296.272), (139, 13995.28)]

,[(334, 28161.025), (74, 6320.272), (244, 20600.842), (94, 8000.706), (174, 14720.587), (99, 8420.104), (484, 40761.531), (493, 41517.869), (447, 37652.765), (49, 4220.412), (499, 42021.241), (298, 25137.81), (79, 6740.362), (169, 14301.015), (439, 36981.933), (216, 18249.141), (476, 40090.247), (462, 38913.015), (413, 34798.204), (480, 40424.342), (491, 41349.055), (150, 12704.648), (433, 36477.326), (13, 1196.272), (400, 33705.346), (114, 9680.556), (127, 10772.474), (62, 5312.143), (295, 24884.463), (230, 19425.274)]

,[(95, 4765.293), (138, 6872.432), (433, 21328.028), (432, 21280.189), (418, 20592.642), (344, 16967.601), (6, 404.037), (280, 13830.566), (175, 8685.604), (107, 5353.385), (487, 23975.472), (311, 15349.847), (473, 23288.902), (137, 6823.531), (427, 21033.375), (181, 8980.196), (453, 22308.892), (411, 20249.344), (328, 16183.891), (462, 22750.113), (407, 20054.791), (480, 23630.328), (31, 1629.26), (26, 1384.165), (170, 8440.836), (160, 7950.83), (58, 2952.176), (451, 22210.281), (43, 2217.416), (258, 12752.142)]

,[(353, 36485.204), (305, 31540.781), (117, 12176.054), (130, 13515.348), (25, 2700.292), (120, 12485.819), (436, 45035.347), (254, 26287.979), (168, 17429.391), (484, 49979.295), (283, 29274.878), (112, 11661.515), (285, 29480.534), (173, 17944.669), (188, 19489.607), (371, 38339.416), (110, 11455.441), (49, 5172.438), (176, 18253.645), (72, 7541.458), (23, 2494.27), (262, 27111.683), (95, 9910.366), (175, 18150.397), (185, 19180.361), (133, 13824.115), (229, 23712.332), (27, 2906.355), (129, 13412.875), (381, 39369.318)]]



# 需要拟合的函数
def f_1(x, A, B):
	return A * x + B



for items in a:
	# 需要拟合的数据组
	x_group = []
	y_group = []
	for x, y in items:
		x_group.append(x)
		y_group.append(y)

	#print(x_group,y_group)
	# 得到返回的A,B值
	A, B = op.curve_fit(f_1, x_group, y_group)[0]
	A = round(A)
	B = round(B)
	print(chr(A)+chr(B),end='')
	#数据点与原先的进行画图比较
	plt.scatter(x_group, y_group, marker='o',label='real')
	x = np.arange(0, 15, 0.01)
	y = A * x + B
	plt.plot(x, y,color='red',label='curve_fit')
	plt.legend()
	plt.title('%.5fx%.5f=y' % (A, B))
plt.show()

UsbKeyboardDataHacker

#!/usr/bin/env python

import sys
import os

DataFileName = "usb.dat"

presses = []

normalKeys = {"04":"a", "05":"b", "06":"c", "07":"d", "08":"e", "09":"f", "0a":"g", "0b":"h", "0c":"i", "0d":"j", "0e":"k", "0f":"l", "10":"m", "11":"n", "12":"o", "13":"p", "14":"q", "15":"r", "16":"s", "17":"t", "18":"u", "19":"v", "1a":"w", "1b":"x", "1c":"y", "1d":"z","1e":"1", "1f":"2", "20":"3", "21":"4", "22":"5", "23":"6","24":"7","25":"8","26":"9","27":"0","28":"<RET>","29":"<ESC>","2a":"<DEL>", "2b":"\t","2c":"<SPACE>","2d":"-","2e":"=","2f":"[","30":"]","31":"\\","32":"<NON>","33":";","34":"'","35":"<GA>","36":",","37":".","38":"/","39":"<CAP>","3a":"<F1>","3b":"<F2>", "3c":"<F3>","3d":"<F4>","3e":"<F5>","3f":"<F6>","40":"<F7>","41":"<F8>","42":"<F9>","43":"<F10>","44":"<F11>","45":"<F12>"}

shiftKeys = {"04":"A", "05":"B", "06":"C", "07":"D", "08":"E", "09":"F", "0a":"G", "0b":"H", "0c":"I", "0d":"J", "0e":"K", "0f":"L", "10":"M", "11":"N", "12":"O", "13":"P", "14":"Q", "15":"R", "16":"S", "17":"T", "18":"U", "19":"V", "1a":"W", "1b":"X", "1c":"Y", "1d":"Z","1e":"!", "1f":"@", "20":"#", "21":"$", "22":"%", "23":"^","24":"&","25":"*","26":"(","27":")","28":"<RET>","29":"<ESC>","2a":"<DEL>", "2b":"\t","2c":"<SPACE>","2d":"_","2e":"+","2f":"{","30":"}","31":"|","32":"<NON>","33":"\"","34":":","35":"<GA>","36":"<","37":">","38":"?","39":"<CAP>","3a":"<F1>","3b":"<F2>", "3c":"<F3>","3d":"<F4>","3e":"<F5>","3f":"<F6>","40":"<F7>","41":"<F8>","42":"<F9>","43":"<F10>","44":"<F11>","45":"<F12>"}

def main():
    # check argv
    if len(sys.argv) != 2:
        print("Usage : ")
        print("        python UsbKeyboardHacker.py data.pcap")
        print("Tips : ")
        print("        To use this python script , you must install the tshark first.")
        print("        You can use `sudo apt-get install tshark` to install it")
        print("Author : ")
        print("        WangYihang <wangyihanger@gmail.com>")
        print("        If you have any questions , please contact me by email.")
        print("        Thank you for using.")
        exit(1)

    # get argv
    pcapFilePath = sys.argv[1]
    
    # get data of pcap
    os.system("tshark -r %s -T fields -e usb.capdata 'usb.data_len == 8' > %s" % (pcapFilePath, DataFileName))

    # read data
    with open(DataFileName, "r") as f:
        for line in f:
            presses.append(line[0:-1])
    # handle
    result = ""
    for press in presses:
        if press == '':
            continue
        if ':' in press:
            Bytes = press.split(":")
        else:
            Bytes = [press[i:i+2] for i in range(0, len(press), 2)]
        if Bytes[0] == "00":
            if Bytes[2] != "00" and normalKeys.get(Bytes[2]):
                result += normalKeys[Bytes[2]]
        elif int(Bytes[0],16) & 0b10 or int(Bytes[0],16) & 0b100000: # shift key is pressed.
            if Bytes[2] != "00" and normalKeys.get(Bytes[2]):
                result += shiftKeys[Bytes[2]]
        else:
            print("[-] Unknow Key : %s" % (Bytes[0]))
    print("[+] Found : %s" % (result))

    # clean the temp data
    os.system("rm ./%s" % (DataFileName))


if __name__ == "__main__":
    main()

键盘坐标密码

a = "11 11".split(' ')
key_list = [['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],
            ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'],
            ['z', 'x', 'c', 'v', 'b', 'n', 'm']
            ]
print(a)
for index in a:

    for i,key_lists in enumerate(key_list):
        for i2,key in enumerate(key_lists):

            if str(i+1)+str(i2+1) == index:


                print(key,end='')

仿射密码爆破脚本

#auther:mzq
secret = 'fvwm{08k54wf606137wwy9d7w9r230078r7w4}'

def c_1(m):
    f = 1
    while 1:
        if m*f%26 == 1:
            break
        f +=1
    return f
def decode_c(a,b,secret):

    for i in secret:
        if ord(i) >= ord("a") and ord(i) <= ord("z"):
            print(chr(97+(ord(i)-97-b)*a%26),end='')
        else:
            print(i,end='')
    print()
for x in range(1,100):
    for y in range(1,100):

        decode_c(x,y,secret)

杰斐逊转轮解密

a = """roller_list""".split('\n')
secret = 'secret_data'
for i,flag in zip(a,secret):
    print(i[i.index(flag):] + i[:i.index(flag)])

求峰值曲线角度

from math import atan2

sinP = []
sinN = []
cosP = []
cosN = []

data = open("adc.csv").readlines()
data = data[1:]

for i in data:
    s = i.strip().split(",")
    sinP.append(s[0])
    sinN.append(s[1])
    cosP.append(s[2])
    cosN.append(s[3])
data_li = []
for i in range(len(sinP)):
    sinP_ = float(sinP[i])
    sinN_ = float(sinN[i])
    cosP_ = float(cosP[i])
    cosN_ = float(cosN[i])
    sinX = (sinP_-sinN_)*1.0
    cosX = (cosP_-cosN_)*1.0

    tanX = atan2(sinX,cosX)
    angle = tanX*57.29
    data_li.append(angle)
print(len(data_li))
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
x_data = [x for x in range(len(data_li))]
y_data = data_li

plt.plot(x_data,y_data,color='red',linewidth=2.0,linestyle='--')

plt.show()

uuencode隐写解密

def is_line_contain_flag(line):
    left = line[0] - 32
    return left * 4 % 3


def get_hidden_bits(line):
    left = is_line_contain_flag(line)
    assert (left != 0)
    if left == 1:
        return (line[-3] - 32) & 0b1111
    else:
        return (((line[-2] - 32) & 0b11) << 2) | (((line[-1] - 32) & 0b1100) >> 2)  # 提取隐藏的flag bits


if __name__ == '__main__':
    fin = open("poem.txt", "r")
    fout = open("flag.txt", "w")

    enc_lines = fin.read().splitlines()
    enc_lines = list(
        map(lambda x: bytes(x, encoding='ascii'), enc_lines))
    lines_contain_flag = []
    flag = ''
    for i in enc_lines:
        if is_line_contain_flag(i):
            lines_contain_flag.append(i)
        else:
            continue
    for i in range(len(lines_contain_flag)):
        if i % 2 == 0:  # ????
            flag_chr = (get_hidden_bits(lines_contain_flag[i]) << 4) | (get_hidden_bits(lines_contain_flag[i + 1]))
            flag += chr(flag_chr)
    fout.write(flag)
    fin.close()
    fout.close()

Polybius Square Cipher

import itertools
s="aeoiu"
ciper="ouauuuoooeeaaiaeauieuooeeiea"
sumresult=[]
numsumresult=[]
for i in itertools.permutations(s,5):#找出所有全排列
    sumresult.append("".join(i))
for i in sumresult:
    temp=""
    for j in ciper:
        temp+=str(i.index(j)+1)
    numsumresult.append(temp)
for i in numsumresult:
    flag=""
    for j in range(0, len(i),2):
        xx=(int(i[j])-1)*5+int(i[j+1])+96
        if xx>ord('i'):
            xx+=1
        flag+=chr(xx)
    print(flag)

六十四卦编码解密

import base64
import binascii

xianTian64Gua=[
	"坤","剥","比","观","豫","晋","萃","否",
	"谦","艮","蹇","渐","小过","旅","咸","遁",
	"师","蒙","坎","涣","解","未济","困","讼",
	"升","蛊","井","巽","恒","鼎","大过","姤",
	"复","颐","屯","益","震","噬嗑","随","无妄",
	"明夷","贲","既济","家人","丰","离","革","同人",
	"临","损","节","中孚","归妹","睽","兑","履",
	"泰","大畜","需","小畜","大壮","大有","夬","乾"
]
base64Map='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
filepath = "flag.bin"
string = open("flxg.txt","r",encoding="utf-8")
flxg = string.read()
for index, value in enumerate(xianTian64Gua):
    flxg=flxg.replace(value,base64Map[index])
flag = base64.b64decode(flxg)
binfle=open(filepath,"wb+")
binfle.write(flag)# binfle.close()
print(flag)

读取图片像素值

from PIL import Image

img = Image.open('png.png')

width,height = img.size
print(img.mode)
pix_list = []
print(img.size)
for w in range(width):
    for h in range(height):
        pix = img.getpixel((w,h))
        r,g,b,a = pix
        print(b,a)

筛选SQL注入数据

import re

with open('log') as f:
    tmp = f.read()
    flag = ''
    data = re.findall(r'=(\d*)%23',tmp)
    data = [int(i) for i in data]
    for i,num in enumerate(data):
        try:
            if num > data[i+1]:
                flag += chr(num)
        except Exception:
            pass
    print flag

词频分析

from collections import Counter


f=open('file.txt','r')
f_read=f.read()


print Counter(f_read)
a=sorted(Counter(f_read).items(),key=lambda d:d[1],reverse=1)
print ''.join([i[0] for i in a])

0 and 1 转成二维码

import PIL
from PIL import Image


max = 32
img = Image.new('RGB',(max,max))
str = ''
i = 0
for y in range(0,max):
    for x in range(0,max):
        if(str[i] == '1'):
            img.putpixel([x,y],(0,0,0))
        else:
            img.putpixel([x,y],(255,255,255))
        i += 1

img.show()
  • 7
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值