from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from os import urandom as random_bytes class main_aes256: def __init__(self, salt_value, pwd, plaintext=b'', ciphertext=b''): # 初始化方法(构造函数) self.pwd = pwd kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt_value, iterations=100000, backend=default_backend() ) self.key = kdf.derive(pwd) self.plaintext = plaintext self.ciphertext = ciphertext def encrypt(self): # 加密函数 padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_plaintext = padder.update(self.plaintext) + padder.finalize() iv = random_bytes(16) cipher = Cipher(algorithms.AES(self.key), modes.CBC(iv), backend=default_backend()) encryptor = cipher.encryptor() ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize() return iv + ciphertext def decrypt(self): # 解密函数 iv = self.ciphertext[:16] ciphertext = self.ciphertext[16:] cipher = Cipher(algorithms.AES(self.key), modes.CBC(iv), backend=default_backend()) decryptor = cipher.decryptor() padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder() plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() return plaintext password = b"your_password" salt = b"your_salt" plaintext1 = b"Hello, AES-256!" aes256_en1 = main_aes256(salt, password, plaintext=plaintext1) # 加密 ciphertext1 = aes256_en1.encrypt() aes256_de1 = main_aes256(salt, password, ciphertext=ciphertext1) # 解密 decrypted_plaintext1 = aes256_de1.decrypt() print("Plaintext: ", plaintext1) print("Ciphertext: ", ciphertext1) print("Decrypted Plaintext: ", decrypted_plaintext1)
12-15
2810
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-19
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交