Python實現AES加密解密

2021-10-07 20:46:27 字數 2587 閱讀 5070

報錯:

typeerror: decrypt() cannot be called after encrypt()
原因:

cryptor不能寫在主函式中同時給加密函式與解密函式使用,儘管加密解密都是用: cryptor = aes.new(key, mode, iv),

但若將其定義在main並分別傳給加密解密同時使用時,會報錯。

解決:在加密與解密方法分別寫cryptor = aes.new(key, mode, iv)

報錯:

valueerror: incorrect iv length (it must be 16 bytes long)
原因:

偏移量必須16位

報錯:

valueerror: incorrect aes key length
原因:

金鑰長度需為16的倍數

注意:需加密的內容必須大於金鑰長度且為16倍數

實現:

from binascii import b2a_hex, a2b_hex

from crypto.cipher import aes

# 金鑰在使用該方法時可補足為16倍數

# 偏移量在使用該方法時,在不足16位時補為16位

# 偏移量必須為16位,不可多

def legth(value):

l = len(value)

flag = l % 16

if flag != 0:

add = 16 - (l % 16)

value = value + ('\0' * add).encode('utf-8')

return value

def encryp_str(content, key, mode, iv):

cryptor = aes.new(key, mode, iv)

# 被加密內容需大於金鑰長度,且為16倍數

key_length = len(key)

content_legth = len(content)

if content_legth < key_length:

add = key_length - content_legth

content = content + ('\0' * add).encode('utf-8')

elif content_legth > key_length:

add = 16 - (content_legth % 16)

content = content + ('\0' * add).encode('utf-8')

cipher_content = cryptor.encrypt(content) # 加密

print('加密1:', cipher_content)

cipher_content_hex = b2a_hex(cipher_content)

print('加密2:', cipher_content_hex)

cipher_content_hex_de = cipher_content_hex.decode()

print('密文:', cipher_content_hex_de)

return cipher_content_hex_de

def decryp_str(en_content, key, mode, iv):

cryptor = aes.new(key, mode, iv)

content = a2b_hex(en_content)

print('解密1:', content)

content = cryptor.decrypt(content)

print('解密2:', content)

content = bytes.decode(content).rstrip('\0')

print('明文:', content)

return content

if __name__ == '__main__':

# 加密內容

content = input('輸入加密內容:')

# 金鑰

key = input('輸入金鑰:')

key = key.encode('utf-8') # 金鑰需編碼

# 偏移量

iv = input(r'輸入偏移量(16位),少於16位將使用「\0」自動補齊:')

print('原文:', content)

content = content.encode('utf-8') # 編碼加密內容

iv = iv.encode('utf-8')

# 處理key和iv長度

key = legth(key)

iv = legth(iv)

mode = aes.mode_cbc # 加密模式

en_content = encryp_str(content, key, mode, iv)

content = decryp_str(en_content, key, mode, iv)

效果:

Python 實現 AES 加密 解密

一 前言 金鑰 k 用來加密明文的密碼,在對稱加密演算法中,加密與解密的金鑰是相同的。金鑰為接收方與傳送方協商產生,但不可以直接在網路上傳輸,否則會導致金鑰洩漏,通常是通過非對稱加密演算法加密金鑰,然後再通過網路傳輸給對方,或者直接面對面商量金鑰。金鑰是絕對不可以洩漏的,否則會被攻擊者還原密文,竊取...

python 乍見(實現AES 加密解密)

coding utf8 import sysfrom crypto.cipher import aesfrom binascii import b2a hex,a2b hex class prpcrypt def init self,key self.key key self.mode aes.mo...

python實現AES的加密解密

了解aes aes advanced encryption standard 是一種對稱加密演算法,相較於des和3des演算法而言,aes演算法有著更高的速度和資源使用效率,安全級別也較之更高 公式 c e k,p 明文p,金鑰k,aes加密函式組成e,密文c。主要要了解以下幾點 aes金鑰的長度...