DESpython实现代码
时间: 2024-05-02 10:15:15 浏览: 98
DES(Data Encryption Standard)是一种对称加密算法,用于数据的加密和解密。下面是一个简单的Python实现代码示例:
```python
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
def des_encrypt(key, plaintext):
cipher = DES.new(key, DES.MODE_ECB)
padded_plaintext = pad(plaintext.encode(), DES.block_size)
ciphertext = cipher.encrypt(padded_plaintext)
return ciphertext.hex()
def des_decrypt(key, ciphertext):
cipher = DES.new(key, DES.MODE_ECB)
decrypted_data = cipher.decrypt(bytes.fromhex(ciphertext))
plaintext = unpad(decrypted_data, DES.block_size).decode()
return plaintext
# 示例使用
key = b'abcdefgh'
plaintext = 'Hello, DES!'
ciphertext = des_encrypt(key, plaintext)
decrypted_text = des_decrypt(key, ciphertext)
print("Plaintext:", plaintext)
print("Ciphertext:", ciphertext)
print("Decrypted text:", decrypted_text)
```
请注意,上述代码使用了`pycryptodome`库来实现DES算法。在运行代码之前,需要先安装`pycryptodome`库,可以使用以下命令进行安装:
```
pip install pycryptodome
```
阅读全文