用python实现对称密码算法aes和des的代码
时间: 2024-03-14 11:43:44 浏览: 101
下面是使用Python实现AES和DES的示例代码:
AES加密解密示例代码:
```python
from Crypto.Cipher import AES
import base64
# 加密函数
def aes_encrypt(key, data):
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
data = data.encode('utf-8')
# 补全16位
length = 16 - (len(data) % 16)
data += bytes([length]) * length
ciphertext = cipher.encrypt(data)
# 转换为base64编码
return base64.b64encode(ciphertext).decode('utf-8')
# 解密函数
def aes_decrypt(key, ciphertext):
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# 解码base64
ciphertext = base64.b64decode(ciphertext)
data = cipher.decrypt(ciphertext)
# 去除补位
length = data[-1]
data = data[:-length]
return data.decode('utf-8')
# 测试
key = '0123456789abcdef'
data = 'hello world'
ciphertext = aes_encrypt(key, data)
print(ciphertext)
plaintext = aes_decrypt(key, ciphertext)
print(plaintext)
```
DES加密解密示例代码:
```python
from Crypto.Cipher import DES
import base64
# 加密函数
def des_encrypt(key, data):
cipher = DES.new(key.encode('utf-8'), DES.MODE_ECB)
data = data.encode('utf-8')
# 补全8位
length = 8 - (len(data) % 8)
data += bytes([length]) * length
ciphertext = cipher.encrypt(data)
# 转换为base64编码
return base64.b64encode(ciphertext).decode('utf-8')
# 解密函数
def des_decrypt(key, ciphertext):
cipher = DES.new(key.encode('utf-8'), DES.MODE_ECB)
# 解码base64
ciphertext = base64.b64decode(ciphertext)
data = cipher.decrypt(ciphertext)
# 去除补位
length = data[-1]
data = data[:-length]
return data.decode('utf-8')
# 测试
key = '01234567'
data = 'hello world'
ciphertext = des_encrypt(key, data)
print(ciphertext)
plaintext = des_decrypt(key, ciphertext)
print(plaintext)
```
注意:这里仅提供示例代码,实际使用需要根据具体情况进行调整和优化。同时,使用对称密码算法时,需要注意密钥的安全性和保密性。
阅读全文