AES-128算法的CFB(Cipher Feedback)模式加密解密代码
时间: 2024-11-27 14:12:33 浏览: 7
AES(Advanced Encryption Standard)是一种广泛使用的块密码,其中AES-128是一种使用128位密钥的版本。CFB (Cipher Feedback) 模式是一种流加密技术,它将每个输入块与前一个密文块进行异或操作,然后再进行AES加密。下面是一个简单的Python示例,使用pycryptodome库实现AES-CFB模式:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def aes_cfb_encrypt(plaintext, key):
cipher = AES.new(key, AES.MODE_CFB, iv=get_random_bytes(AES.block_size))
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size)) + cipher.iv
return ciphertext
def aes_cfb_decrypt(ciphertext, key):
cipher = AES.new(key, AES.MODE_CFB, iv=ciphertext[:AES.block_size])
plaintext = unpad(cipher.decrypt(ciphertext[AES.block_size:]), AES.block_size).decode()
return plaintext
# 示例
key = b'sixteen byte key' # 使用16字节AES密钥
plaintext = "Hello, CFB mode!"
ciphertext = aes_cfb_encrypt(plaintext, key)
decrypted_text = aes_cfb_decrypt(ciphertext, key)
print(f"Plaintext: {plaintext}")
print(f"Ciphertext: {ciphertext.hex()}")
print(f"Decrypted Text: {decrypted_text}")
```
注意:在实际应用中,你需要妥善管理IV,通常它会被发送并与密文一起传输,确保它是随机生成且保密的。
阅读全文