aes加密代码python
时间: 2023-11-09 14:01:05 浏览: 42
以下是使用pycryptodome库实现AES加密的Python代码:
```python
from Crypto.Cipher import AES
import base64
def aes_encrypt(key, data):
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
pad = lambda s: s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
encrypted_data = cipher.encrypt(pad(data).encode('utf-8'))
return base64.b64encode(encrypted_data).decode('utf-8')
```
其中,`key`为加密密钥,`data`为待加密的数据。加密结果为base64编码后的字符串。
相关问题
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位长。
AES加密算法python
以下是使用Python中的pycryptodome模块进行AES加密和解密的示例代码:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
# 加密函数
def encrypt_AES(data, key, iv):
cipher = AES.new(key, AES.MODE_CBC, iv)
encrypted = cipher.encrypt(pad(data.encode('utf-8'), AES.block_size))
# 将加密后的数据进行base64编码
return base64.b64encode(encrypted).decode('utf-8')
# 解密函数
def decrypt_AES(data, key, iv):
cipher = AES.new(key, AES.MODE_CBC, iv)
# 先将base64编码的数据解码
decrypted = cipher.decrypt(base64.b64decode(data))
# 去除解密后的数据中的填充字节
return unpad(decrypted, AES.block_size).decode('utf-8')
# 测试代码
if __name__ == '__main__':
key = b'sixteen byte key'
iv = b'initial vector '
data = 'hello world!'
encrypted_data = encrypt_AES(data, key, iv)
print('加密后的数据:', encrypted_data)
decrypted_data = decrypt_AES(encrypted_data, key, iv)
print('解密后的数据:', decrypted_data)
```
以上代码中,我们使用16字节的密钥和16字节的初始向量(IV)进行AES加密和解密,同时对加密后的数据进行了base64编码,使其更易于传输。