from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto.Protocol.KDF import PBKDF2 def generate_key_and_iv(password, salt, key_size=32, iv_size=16): key_iv = PBKDF2(password, salt, dkLen=key_size + iv_size, count=100000) return key_iv[:key_size], key_iv[key_size:] def encrypt_AES_CBC(message, password): salt = get_random_bytes(16) key, iv = generate_key_and_iv(password, salt) cipher = AES.new(key, AES.MODE_CBC, iv) #ciphertext = cipher.encrypt(pad(message.encode('utf-8'), [①])) ciphertext = cipher.encrypt(pad(message.encode('utf-8'), AES.block_size)) return salt + ciphertext def decrypt_AES_CBC(ciphertext, password): salt = ciphertext[:16] #ciphertext = ciphertext[②] ciphertext = ciphertext[16:] key, iv = generate_key_and_iv(password, salt) cipher = AES.new(key, AES.MODE_CBC, iv) decrypted_message = unpad(cipher.decrypt(ciphertext), AES.block_size) return decrypted_message.decode('utf-8') def pad(message, block_size): #padding_size = block_size - len(message) % [③] padding_size = block_size - len(message) % block_size padding = bytes([padding_size] * padding_size) return message + padding def unpad(padded_message, block_size): #padding_size = [④] padding_size = padded_message[-1] if padding_size < 1 or padding_size > block_size: raise ValueError("Invalid padding") if padded_message[-padding_size:] != bytes([padding_size] * padding_size): raise ValueError("Invalid padding") return padded_message[:-padding_size] if __name__ == "__main__": # 要加密的消息和密码 message = "Hello, this is a message to be encrypted using AES!" password = "1234456" # 加密46 encrypted_data = encrypt_AES_CBC(message, password) print("Encrypted:", encrypted_data) # 解密 decrypted_message = decrypt_AES_CBC(encrypted_data, password) print("Decrypted:", decrypted_message)
AES的加解密-python样例程序
最新推荐文章于 2024-01-15 01:14:20 发布