base64

百度了一会base64,在吾爱破解上发现了一篇讲解很详细的文章,于是尝试自己实现base64加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
letters=['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','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','0', '1', '2', '3','4','5','6','7','8','9','+', '/']
def encode(str_input):
str_output=''
list_input=['{:0>8}'.format(str(bin(ord(str_input[i]))).replace('0b', '')) for i in range(len(str_input))]
compensate=0
while list_input:
list_temp=list_input[:3]
while len(list_temp)%3:
compensate+=1
list_temp.append('0'*8)
str_temp=''.join(list_temp)
list_str_temp=[str_temp[i:i+6] for i in [0,6,12,18]]
list_str_temp=[int(i,2) for i in list_str_temp]
str_output+=''.join(letters[i] for i in list_str_temp)
list_input=list_input[3:]
str_output+='='*compensate
return str_output
def decode(str_input):
str_output=''
list_input=['{:0>6}'.format(str(bin(letters.index(i))).replace('0b', ''))for i in str_input if i != '=']
compensate=0
for i in str_input:
if i == '=':
compensate+=1
while list_input:
list_temp=list_input[:4]
str_temp=''.join(list_temp)
while len(str_temp)%8:
str_temp=str_temp[0:-1*2*compensate]
list_str_temp=[str_temp[i:i+8] for i in [0,8,16]]
print list_str_temp
list_str_temp2=['00000000' if i =='' else i for i in list_str_temp]
print list_str_temp2
list_str_temp=[int(i,2) for i in list_str_temp2]
str_output+=''.join([chr(i)for i in list_str_temp])
list_input=list_input[4:]
return str_output


s="sadadsadaddasdadas"
d='c2FkYWRzYWRhZGRhc2RhZGFz'
print encode(s)
print decode(d)

运行:

1
2
3
sH1rkEr:desktop macbook$ python base64.py
c2FkYWRzYWRhZGRhc2RhZGFz
sadadsadaddasdadas
文章目录
|