const crypto = require('crypto');function encryptAES(text, key) { const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv('aes-256-cbc', key, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); return iv.toString('hex') + ':' + encrypted;}function decryptAES(encryptedText, key) { const parts = encryptedText.split(':'); const iv = Buffer.from(parts.shift(), 'hex'); const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); let decrypted = decipher.update(parts.join(':'), 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted;}// 测试const key = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6';const text = 'Hello, world!';const encrypted = encryptAES(text, key);console.log('Encrypted:', encrypted);const decrypted = decryptAES(encrypted, key);console.log('Decrypted:', decrypted);,帮我把这段代码转成python
时间: 2023-09-12 18:08:03 浏览: 162
node.JS的crypto加密模块使用方法详解(MD5,AES,Hmac,Diffie-Hellman加密)
以下是将上述Node.js的AES加密函数转化为Python的代码:
```python
import os
from Crypto.Cipher import AES
def encryptAES(text, key):
iv = os.urandom(16)
cipher = AES.new(key.encode(), AES.MODE_CBC, iv)
encrypted = cipher.encrypt(pad(text.encode(), AES.block_size))
return iv.hex() + ':' + encrypted.hex()
def decryptAES(encryptedText, key):
parts = encryptedText.split(':')
iv = bytes.fromhex(parts[0])
encrypted = bytes.fromhex(parts[1])
cipher = AES.new(key.encode(), AES.MODE_CBC, iv)
decrypted = unpad(cipher.decrypt(encrypted), AES.block_size)
return decrypted.decode()
def pad(s, block_size):
padding = block_size - len(s) % block_size
return s + padding * chr(padding).encode()
def unpad(s, block_size):
padding = s[-1]
if padding < 1 or padding > block_size:
raise ValueError("Invalid padding")
if any(s[-i] != padding for i in range(1, padding+1)):
raise ValueError("Invalid padding")
return s[:-padding]
# 测试
key = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
text = 'Hello, world!'
encrypted = encryptAES(text, key)
print('Encrypted:', encrypted)
decrypted = decryptAES(encrypted, key)
print('Decrypted:', decrypted)
```
这个函数使用了Python的Crypto模块,使用AES-256-CBC算法进行加密和解密。在加密时,我们使用一个随机生成的16字节的初始向量iv,将其与密文一起返回。在解密时,我们从加密文本中提取出iv,并使用它来创建解密器。
阅读全文