from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
def des_encrypt(plaintext: str, key: bytes) -> bytes:
cipher = Cipher(algorithms.DES(key), modes.ECB(), backend=default_backend())
encryptor = cipher.encryptor()
return encryptor.update(plaintext.encode()) + encryptor.finalize()
def des_decrypt(ciphertext: bytes, key: bytes) -> str:
cipher = Cipher(algorithms.DES(key), modes.ECB(), backend=default_backend())
decryptor = cipher.decryptor()
return decryptor.update(ciphertext).decode()
# Example key (must be 8 bytes long)
key = b'secretkey'
# Example plaintext
plaintext = 'Hello, World!'
# Encrypt the plaintext
ciphertext = des_encrypt(plaintext, key)
print("Encrypted:", ciphertext)
# Decrypt the ciphertext
decrypted_text = des_decrypt(ciphertext, key)
print("Decrypted:", decrypted_text)
为什么这段代码会出错? 此附加代码适用于 DES 算法 附上错误显示的图片 我找不到错误 该代码是DES算法的加密和解密
我猜是因为你没有从 Crypto.Cipher 导入 DES