python代码实现des加解密算法
时间: 2023-07-25 18:21:36 浏览: 51
以下是Python实现DES加解密算法的示例代码:
```python
from Crypto.Cipher import DES
def des_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)
return ciphertext
def des_decrypt(key, ciphertext):
cipher = DES.new(key, DES.MODE_ECB)
padded_plaintext = cipher.decrypt(ciphertext)
plaintext = padded_plaintext[:-ord(padded_plaintext[-1])]
return plaintext
key = b"abcdefgh" # 8字节的密钥
plaintext = "Hello, World!" # 明文
ciphertext = des_encrypt(key, plaintext.encode())
decrypted_plaintext = des_decrypt(key, ciphertext).decode()
print("Ciphertext:", ciphertext)
print("Decrypted plaintext:", decrypted_plaintext)
```
需要注意的是,Python中的DES实现需要安装Crypto库,可以使用以下命令进行安装:
```
pip install pycrypto
```