AES算法与SHA512哈希算法是两种独立的加密方式,AES算法不会直接将SHA512纳入其算法中。但可以通过使用SHA512对AES密钥进行哈希加密,以提高密钥的安全性。示例代码如下:
import hashlib import os from Crypto.Cipher import AES
def encrypt_AES_CBC(msg, password): # 使用SHA512哈希加密密码 password = hashlib.sha512(password.encode()).digest() # 生成随机的IV向量 iv = os.urandom(16) # 使用AES-CBC加密 cipher = AES.new(password, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(msg.encode()) return (ciphertext, iv)
def decrypt_AES_CBC(ciphertext, iv, password): # 使用SHA512哈希加密密码 password = hashlib.sha512(password.encode()).digest() # 使用AES-CBC解密 cipher = AES.new(password, AES.MODE_CBC, iv) msg = cipher.decrypt(ciphertext).decode() return msg
plaintext = "Hello, AES!" password = "password" ciphertext, iv = encrypt_AES_CBC(plaintext, password) decrypted = decrypt_AES_CBC(ciphertext, iv, password)
print("PlainText :", plaintext) print("CipherText:", ciphertext) print("Decrypted :", decrypted)