1. 程式人生 > >python中base64加密和解密

python中base64加密和解密

base64加密和解密有點頭疼,必須要記錄下來,以後忘了也能再來複習下 當然啦,能一直記住是最好的…加油吧,少年(其實已經好老了)

操作環境

win10,python3

base的原理

簡單小案例

其實它的原理不是很難,以下是幾個小案例

import base64
str='admin'
str=str.encode('utf-8')
#加密
bs64=base64.b64encode(str)
print(bs)
#結果是  b'YWRtaW4='

bs32=base64.b32encode(str)
print(bs32)
#結果是  b'MFSG22LO'

bs16=base64.b16encode(
str) print(bs16) #結果是 b'61646D696E' #解密 debs64=base64.b64decode(bs64) print(debs64) #結果是 b'admin' debs32=base64.b32decode(bs32) print(debs32) #結果是 b'admin' debs16=base64.b16decode(bs16) print(debs16) #結果是 b'admin'

b64,b32,b16的混合加密和解密

請看程式碼:

import base64
import random
#flag="flag{**some seclet**}"
#base64加密 def base64_encode(flag): #定義編碼方式 basecode={ '16':lambda x:base64.b16encode(x), '32':lambda x:base64.b32encode(x), '64':lambda x:base64.b64encode(x) } #將‘str’型別轉換成‘bytes’型別 pp=flag.encode('utf-8') #進行迴圈編碼 for i in range(10): order=
random.choice(['16','32','64']) pp=basecode[order](pp) #將‘bytes’型別轉換成‘str’型別 pp=pp.decode('utf-8') #寫入檔案中 with open("ciphertext.txt",'w') as fp: fp.write(pp) return '###加密成功###' #base64解密 def base64_decode(ciphertext): result='' with open(ciphertext+".txt",'r') as fp: ciphertext=fp.read() ciphertext=ciphertext.encode('utf-8') #定義解密方式 basedecode={ '16':lambda x:base64.b16decode(x), '32':lambda x:base64.b32decode(x), '64':lambda x:base64.b64decode(x) } for j in range(10): try: ciphertext=basedecode['16'](ciphertext) except: try: ciphertext=basedecode['32'](ciphertext) except: ciphertext=basedecode['64'](ciphertext) result=ciphertext.decode('utf-8') print(result) return '###解密成功###' def main(): functions=input('輸入A加密,輸入B解密,其它關閉>>>') if functions=='A': plaintext=input('請輸入加密文字明文>>>') print(base64_encode(plaintext)) if functions=='B': ciphertext = input('請輸入密文檔名>>>') print(base64_decode(ciphertext)) if __name__=='__main__': main()

結果展示

runfile('C:/Users/lenovo/Documents/我的python筆記/作業4.py', wdir='C:/Users/lenovo/Documents/我的python筆記')

輸入A加密,輸入B解密,其它關閉>>>>A

請輸入加密文字明文>>>abcdefg
###加密成功###

runfile('C:/Users/lenovo/Documents/我的python筆記/作業4.py', wdir='C:/Users/lenovo/Documents/我的python筆記')

輸入A加密,輸入B解密,其它關閉>>>>B

請輸入密文檔名>>>ciphertext
abcdefg
###解密成功###

注意

在解碼的時候,由於加密的時候是隨機加密的,隨意該怎麼用正確的解碼方式去解碼就成了關鍵。 這裡找了"try…except…"的語句去實現,一個一個方式去試,最終試出明文。