计算文件md5

import hashlib
fp = open("file.txt", "rb")
md5_obj = hashlib.md5()
md5_obj.update(fp.read())
hash_code = md5_obj.hexdigest()
md5 = str(hash_code).lower()
fp.close()

计算字符串md5

def md5(str):
import hashlib
m = hashlib.md5()
m.update(str)
return m.hexdigest()

C语言rand()

  • Windows版
def rand():
global seed
seed = seed * 0x343FD + 0x269EC3
return (seed >> 16) & 0x7FFF

凯撒密码26次

#coding:utf-8

upperDict = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
lowerDict = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


def cesarWithLetter(ciphertext, offset):
'''
凯撒密码 :
只转换字母(包括大写小写)
参数 :
ciphertext : 明文
offset : 偏移量
'''
result = ""
for ch in ciphertext:
if ch.isupper():
result = result+upperDict[((upperDict.index(ch)+offset) % 26)]
elif ch.islower():
result = result+lowerDict[((lowerDict.index(ch)+offset) % 26)]
elif ch.isdigit():
result = result+ch
else:
result = result+ch
return result


def printAllResult(ciphertext):
'''
打印所有偏移结果
'''
for i in range(len(upperDict)):
print cesarWithLetter(ciphertext, i)


ciphertext = raw_input("Please input the words :")
printAllResult(ciphertext)

二进制转字符串

import libum
s = ''
s = int(s, 2)
print(libunm.n2s(s))

扩展欧几里得算法

def egcd(a, b):
x, lastX = 0, 1
y, lastY = 1, 0
while b != 0:
q = a // b
a, b = b, a % b
x, lastX = lastX - q * x, x
y, lastY = lastY - q * y, y
return lastX, lastY

base64隐写解密脚本

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('stego.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()

解压多层压缩包

#encoding: utf-8
import zipfile

def unzip(path, target, pwd=None):
z = zipfile.ZipFile(path)

for name in z.namelist():
if "zip" in name:
print (name)
z.extract(name, target, name[0:-4])

return name

path = "./"
target = "./"
zipname = "onion.zip"
hint = open("hint.txt","r")
pwd = hint.read().script()

while True:
filename = unzip(path + zipname, path)

if "zip" not in filename:
filename = unzip(path + filename, target)
break

Pillow

from PIL import Image,ImageDraw
height = 202
width = 211

"""
for x in range(0,width):
for y in range(0,height):
if x==0 or y == 0:
draw.point((x,y), fill = (255,255,255))
"""
for file in range(1,26):
img = Image.open("./%d.png"%file)

img2 = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(img2)
pix = img.load()
for y in range(2,height-21,22):
for x in range(2,width-22,23):
flag = 0
for xx in range(x+3,x+19):
for yy in range(y+3,y+18):
if pix[xx,yy]==(0,0,0,255):
flag = 1
break
if flag == 1:
break

if flag == 1:
for i in range(x,x+23):
for j in range(y,y+22):
draw.point((i,j),fill = (0,0,0))
img2.save("n%d.png"%file)

莫斯电码

from pwn import *
import morse_talk as mtalk
import libnum
with open('zero_one', 'r') as f:
data = f.read().translate(None, ' \n')
data = data.replace("ZERO","0").replace("ONE","1")
data = b64d(libnum.b2s(data))
data = mtalk.decode(data)
print data.replace("O","_")

ROT13

import string
def rot13(s):
lower_case = string.ascii_lowercase
upper_case = string.ascii_uppercase
lower_transform = lower_case[13:] + lower_case[:13]
upper_transform = upper_case[13:] + upper_case[:13]
def rot_char(c):
c = chr(c)
if c in lower_case:
return lower_transform[lower_case.index(c)]
elif c in upper_case:
return upper_transform[upper_case.index(c)]
else:
return c
return b"".join(str.encode(rot_char(c)) for c in s)

Rail-Fence

#!/usr/bin/env python3
import math

def decode(e, f):
b = math.ceil(e.__len__() / f)
result = {x: '' for x in range(b)}
last_len = e.__len__() - (b - 1) * f

for idx in range(last_len * b):
k = idx % b
result.update({k: result[k] + e[idx]})

e = e[idx + 1:]

for k in range(e.__len__()):
j = k % (b - 1)
result.update({j: result[j] + e[k]})

d = ''
for i in range(b):
d += result[i]
return d

def encode(p, f):
b = math.ceil(p.__len__() / f)
result = {x: '' for x in range(b)}
for i in range(b):
result.update({i: p[i * f: i * f + f]})

e = ''
for j in range(f):
for i in range(b):
try:
e += result[i][j]
except:
pass
return e

if __name__ == "__main__":
e = ""
for i in range(2, e.__len__()):
print(f"{i} : {decode(e, i)}")

bin/hex互转


# -*- coding:utf-8 -*-

import os
import sys
from struct import *

#intel-hex 格式
#:LLAAAARRDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDZZ
#LL——长度,单位,byte
#AAAA——16 bit 地址
#RR——类型
# - 00 数据记录 (data record)
# - 01 结束记录 (end record)
# - 02 扩展段地址记录 (paragraph record)
# - 03 转移地址记录 (transfer address record)
# - 04 扩展线性地址记录 (expand address record)
#DD——16byte数据
#ZZ——校验

last_size = 0
last_addr = 0
cur_size = 0
cur_addr = 0
high_addr = 0
expand_f = 0

#hex to bin
def hex_bin(hexfile,binfile):
#declare global var
global last_size
global last_addr
global cur_size
global cur_addr
global high_addr
global expand_f
fin = open(hexfile)
fout = open(binfile,'wb')
result =''
#read every lines
for hexstr in fin.readlines():
#去空格\n\r\t
# print hexstr
hexstr = hexstr.strip()
size = int(hexstr[1:3],16)
#RR是数据
if int(hexstr[7:9],16) == 0:
#expand addr deal
if expand_f == 1:
cur_addr = int(hexstr[3:7],16)
#data skipped
need_wr_size = high_addr+cur_addr-(last_addr+last_size)
if need_wr_size != 0:
if need_wr_size > 1000:
print ("skipped data too large !!!")
else:
result=''
for dr in range(0,need_wr_size):
#empty space write 0xff
b = int("0xff",16)
result = pack('B',b)
fout.write(result)
expand_f = 0
last_size = size
last_addr = int(hexstr[3:7],16)

for h in range(0, size):
b = int(hexstr[(9+h*2):(9+h*2+2)],16)
result += pack('B',b)
#end if
fout.write(result)
result=''
#RR是结束
elif int(hexstr[7:9],16) == 1:
end_f = 1
#RR是扩展地址
elif int(hexstr[7:9],16) == 4:
high_addr = int(hexstr[9:13],16)
if high_addr:
expand_f = 1
# print hexstr,hex(high_addr),expand_f
#end if
#end for
fin.close()
fout.close()

# bin to hex
def bin_hex(binfile,hexfile):
fbin = open(binfile,'rb')
fhex = open(hexfile,'w')
offset = 0
seg_addr = 0
while 1:
checksum=0
result = ':'
bindata = fbin.read(0x10)
if len(bindata) == 0 :
break
#end if
result += '%02X' % len(bindata)
result += '%04X' % offset
result += '00'
checksum = len(bindata)
checksum += (offset & 0xff) + (offset >> 8)

for i in range(0,len(bindata)):
byte = unpack('B',bindata[i])
result+='%02X' % byte
checksum += byte[0]
#end for
checksum = 0x01 + ~checksum
checksum = checksum & 0xff
result += '%02X/n' % checksum
fhex.write(result)
offset += len(bindata)
if offset == 0x10000:
offset = 0
seg_addr += 1
result = ':02000004'
result += '%02X%02X' % ((seg_addr>>8) & 0xff,seg_addr & 0xff)
checksum = 0x02 + 0x04 + (seg_addr>>8) + seg_addr & 0xff
checksum = -checksum
result+='%02X' % (checksum & 0xff)
result += '/n'
fhex.write(result)
#end if
if len(bindata) < 0x10:
break
#end if
#end while
fhex.write(':00000001FF')
fbin.close()
fhex.close()
#end for

if len(sys.argv) != 4 or (sys.argv[1] != '-h' and sys.argv[1] != '-b'):
print 'usage:'
print 'convert binary format to hexadecimal format: '
print ' hexbin.py -h binfile hexfile'
print 'convert hexadecimal format to binary format:'
print ' hexbin.py -b hexfile binfile'
exit(0)

if sys.argv[1] == '-h':
bin_hex(sys.argv[2],sys.argv[3])
else:
hex_bin(sys.argv[2],sys.argv[3])