用python写一段AES加密算法与DES加密算法的代码
时间: 2023-09-25 16:06:54 浏览: 72
### 回答1:
Python代码:# AES加密
from Crypto.Cipher import AES
key = b'Sixteen byte key'
cipher = AES.new(key, AES.MODE_EAX)
data = b'Hello world'
ciphertext, tag = cipher.encrypt_and_digest(data)# DES加密
from Crypto.Cipher import DES
key = b'12345678'
iv = b'12345678'
des = DES.new(key, DES.MODE_CBC, iv)
data = b'Hello world'
ciphertext = des.encrypt(data)
### 回答2:
以下是使用Python编写的AES加密算法和DES加密算法的代码段:
AES加密算法代码:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad
# 生成随机密钥
key = get_random_bytes(16)
# 设置初始向量
iv = get_random_bytes(16)
# 创建AES cipher对象
cipher = AES.new(key, AES.MODE_CBC, iv)
# 待加密的明文
plaintext = b'This is a secret message'
# 对明文进行加密
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
# 打印加密后的结果
print(ciphertext)
```
DES加密算法代码:
```python
from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad
# 生成随机密钥
key = get_random_bytes(8)
# 设置初始向量
iv = get_random_bytes(8)
# 创建DES cipher对象
cipher = DES.new(key, DES.MODE_CBC, iv)
# 待加密的明文
plaintext = b'This is a secret message'
# 对明文进行加密
ciphertext = cipher.encrypt(pad(plaintext, DES.block_size))
# 打印加密后的结果
print(ciphertext)
```
以上代码使用`pycryptodome`库实现了AES加密算法和DES加密算法。在AES加密算法中,通过生成随机密钥和初始向量,创建AES cipher对象,并使用`encrypt`方法对明文进行加密。DES加密算法的实现类似于AES加密算法,只是使用的是8字节的密钥和初始向量。
### 回答3:
以下是使用Python编写的AES加密算法和DES加密算法的代码:
AES加密算法代码示例:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def aes_encrypt(key, data):
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)
return ciphertext
def aes_decrypt(key, ciphertext):
cipher = AES.new(key, AES.MODE_EAX, nonce=cipher.nonce)
plaintext = cipher.decrypt(ciphertext)
return plaintext
# 使用示例
key = get_random_bytes(16) # AES-128 使用16字节的密钥
data = b'This is a secret message'
encrypted_data = aes_encrypt(key, data)
decrypted_data = aes_decrypt(key, encrypted_data)
print("Encrypted data:", encrypted_data)
print("Decrypted data:", decrypted_data)
```
DES加密算法代码示例:
```python
from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes
def des_encrypt(key, data):
cipher = DES.new(key, DES.MODE_ECB)
padded_data = data + b'\x00' * (8 - len(data) % 8) # 补齐数据长度到8的倍数
ciphertext = cipher.encrypt(padded_data)
return ciphertext
def des_decrypt(key, ciphertext):
cipher = DES.new(key, DES.MODE_ECB)
plaintext = cipher.decrypt(ciphertext)
return plaintext
# 使用示例
key = get_random_bytes(8) # DES使用8字节的密钥
data = b'This is a secret message'
encrypted_data = des_encrypt(key, data)
decrypted_data = des_decrypt(key, encrypted_data)
print("Encrypted data:", encrypted_data)
print("Decrypted data:", decrypted_data)
```
请注意,这里使用了Crypto库来实现加密算法。在运行代码之前,需要先安装Crypto库,可以使用以下命令进行安装:
```
pip install pycryptodome
```
另外,由于加密算法涉及到密钥管理和数据安全等重要问题,请确保在实际使用时采取适当的安全措施。