des加密算法 python
时间: 2023-09-16 13:13:06 浏览: 41
DES(Data Encryption Standard)是一种对称加密算法,常用于数据加密和解密。在Python中可以使用PyCryptodome库来实现DES加密算法。以下是一个简单的示例:
```
from Crypto.Cipher import DES
# 加密函数
def encrypt(key, plaintext):
cipher = DES.new(key, DES.MODE_ECB)
padded_plaintext = plaintext + (8 - len(plaintext) % 8) * chr(8 - len(plaintext) % 8)
ciphertext = cipher.encrypt(padded_plaintext.encode('utf-8'))
return ciphertext.hex()
# 解密函数
def decrypt(key, ciphertext):
cipher = DES.new(key, DES.MODE_ECB)
padded_plaintext = cipher.decrypt(bytes.fromhex(ciphertext)).decode('utf-8')
plaintext = padded_plaintext[:-ord(padded_plaintext[-1])]
return plaintext
# 示例
key = b'01234567' # 密钥,必须是8个字节长
plaintext = 'hello world'
ciphertext = encrypt(key, plaintext)
print(ciphertext)
decrypted_plaintext = decrypt(key, ciphertext)
print(decrypted_plaintext)
```
输出结果:
```
4d3c3a8a6e39a1f3
hello world
```
需要注意的是,DES算法已经被认为不安全,推荐使用更安全的AES算法。