aes加密算法python实现
时间: 2023-09-30 19:05:41 浏览: 66
下面是一份简单的AES加密算法的Python实现代码:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
def encrypt_AES(key, data):
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
padded_data = pad(data.encode('utf-8'), AES.block_size)
encrypted_data = cipher.encrypt(padded_data)
return encrypted_data.hex()
```
其中,`key`是加密的密钥,`data`是要加密的数据。这个函数使用的是ECB模式,对于较长的数据,需要使用更安全的CBC模式。另外,解密的实现也是相似的,只需要将`encrypt`替换为`decrypt`即可。
相关问题
AES加密算法python实现
下面是使用Python实现AES加密的示例代码:
```python
from Crypto.Cipher import AES
import base64
# 加密函数
def encrypt(key, text):
# 将密钥进行Base64编码
key = base64.b64encode(key.encode('utf-8'))
# 将明文进行Padding,使其长度为AES块大小的整数倍
text = text + (AES.block_size - len(text) % AES.block_size) * chr(AES.block_size - len(text) % AES.block_size)
# 创建AES实例,使用CBC模式和PKCS7Padding填充方式
cipher = AES.new(key, AES.MODE_CBC, b'0000000000000000')
# 加密明文
ciphertext = cipher.encrypt(text.encode('utf-8'))
# 将密文进行Base64编码
ciphertext = base64.b64encode(ciphertext)
# 返回加密后的密文
return ciphertext.decode('utf-8')
# 解密函数
def decrypt(key, ciphertext):
# 将密钥进行Base64编码
key = base64.b64encode(key.encode('utf-8'))
# 将密文进行Base64解码
ciphertext = base64.b64decode(ciphertext)
# 创建AES实例,使用CBC模式和PKCS7Padding填充方式
cipher = AES.new(key, AES.MODE_CBC, b'0000000000000000')
# 解密密文
text = cipher.decrypt(ciphertext)
# 去除Padding
text = text[:-ord(text[-1])]
# 返回解密后的明文
return text.decode('utf-8')
# 测试代码
key = '1234567890abcdef'
text = 'Hello, AES!'
ciphertext = encrypt(key, text)
plaintext = decrypt(key, ciphertext)
print('明文:', text)
print('密文:', ciphertext)
print('解密后的明文:', plaintext)
```
需要使用 `pycryptodome` 库安装,可以通过 `pip install pycryptodome` 命令进行安装。在上面的代码中,我们使用AES算法和CBC模式进行加密和解密,并使用PKCS7Padding填充方式对明文进行Padding。在加密时,我们先对密钥进行Base64编码,然后对明文进行Padding并加密,最后将密文进行Base64编码。在解密时,我们先对密钥进行Base64编码,然后对密文进行Base64解码并解密,最后去除Padding得到明文。
aes加密算法python实现代码
以下是Python中使用AES加密算法的示例代码:
```python
from Crypto.Cipher import AES
import base64
# 加密函数
def encrypt(text, key):
# 设定加密算法和初始向量
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# 将明文进行补位操作
text = text + (AES.block_size - len(text) % AES.block_size) * chr(AES.block_size - len(text) % AES.block_size)
# 进行加密操作
ciphertext = cipher.encrypt(text.encode('utf-8'))
# 将加密结果进行base64编码
return base64.b64encode(ciphertext).decode('utf-8')
# 解密函数
def decrypt(text, key):
# 设定解密算法和初始向量
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# 对密文进行base64解码
ciphertext = base64.b64decode(text)
# 进行解密操作
plaintext = cipher.decrypt(ciphertext).decode('utf-8')
# 去除补位字符
return plaintext[:-ord(plaintext[-1])]
# 测试
if __name__ == '__main__':
key = '1234567890123456' # 密钥必须是16、24或32位长
text = 'Hello, world!'
print('明文:', text)
ciphertext = encrypt(text, key)
print('加密后:', ciphertext)
plaintext = decrypt(ciphertext, key)
print('解密后:', plaintext)
```
其中,`encrypt`函数用于加密明文,`decrypt`函数用于解密密文。在此示例中,使用的加密算法为AES,加密模式为ECB,补位方式为PKCS7。请注意,密钥必须是16、24或32位长。