base64
主要思想就是 3*8-->4*6
python
table="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def encrypt(inputstr):
# 输入字符是8的倍数,--> 3*8>4*6
# {:0>8} 左边补0
ascii=['{:0>8}'.format(str(bin(ord(i))).replace('0b','')) for i in inputstr]
encrystr=''
equalnum=0 #need add '='
while ascii:
# every three into a team
subascii=ascii[:3]
# short need add
while len(subascii)<3:
equalnum+=1
subascii+=['0'*8]
# apply substr to gather subascii
substr=''.join(subascii)
# do devied
encrystrlist=[substr[x:x+6] for x in [0,6,12,18]]
# six site change into dec,so not need 位数补齐
encrystrlist=[int(x,2) for x in encrystrlist]
if equalnum:
encrystrlist=encrystrlist[0:4-equalnum]
# 字符对应表映射
encrystr+=''.join(table[x] for x in encrystrlist)
# 每次取三个列表元素,对应while循环条件
ascii=ascii[3:]
encrystr+='='*equalnum
return encrystr
def decrypt(inputstr):
# six site a team
ascii=['{0:0>6}'.format(str(bin(table.index(i))).replace('0b','')) for i in inputstr if i!='=']
decrystr=''
equalnum=inputstr.count('=')
while ascii:
# four site a team
subascii=ascii[:4]
substr=''.join(subascii)
if len(substr)%8!=0:
substr=substr[0:-1*equalnum*2]
decrystrlist=[substr[x:x+8] for x in [0,8,16]]
decrystrlist=[int(x,2)for x in decrystrlist if x]
decrystr+=''.join([chr(x) for x in decrystrlist])
ascii=ascii[4:]
return decrystr
if __name__=="__main__":
print(encrypt('a'))
print(decrypt('YQ=='))
还有一个C版本的