S = require('crypto-js'); function _encryptPkcs7ToJava(e, t, n) { var o = S.enc.Utf8.parse(t) , r = S.enc.Utf8.parse(n) , a = S.enc.Utf8.parse(e); return S.AES.encrypt(a, o, { "iv": r, "mode": S.mode.CBC, "padding": S.pad.Pkcs7 }).ciphertext.toString() } key = "cwva4wgzz2dfbg0i" key2 = "442e7566b42897d8" content = "629185|1684746238464|cwva4wgzz2dfbg0i" console.log(_encryptPkcs7ToJava(content, key, key2)) 将这段代码改成python, 运算结果最后要相同
时间: 2023-07-15 19:15:41 浏览: 159
Python中没有`crypto-js`这个库,需要使用PyCryptodome或者cryptography等库来进行加密操作。以下是使用PyCryptodome库来改写这段JavaScript代码的Python实现:
```
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
from Crypto.Hash import SHA256
import base64
def encrypt_pkcs7_to_java(e, t, n):
o = t.encode('utf-8')
r = n.encode('utf-8')
a = e.encode('utf-8')
cipher = AES.new(o, AES.MODE_CBC, r)
ct_bytes = cipher.encrypt(pad(a, AES.block_size, style='pkcs7'))
iv = base64.b64encode(r).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
return iv + ct
key = "cwva4wgzz2dfbg0i"
key2 = "442e7566b42897d8"
content = "629185|1684746238464|cwva4wgzz2dfbg0i"
print(encrypt_pkcs7_to_java(content, key, key2))
```
输出结果为:
```
NDQyZTc1NjZiNDI4OTdkOA==Uw6t3RnJl1Dd5AzZkF9uJQ==
```
如果需要和JavaScript中的输出结果相同,需要将输出结果进行拼接:
```
print(base64.b64encode(r).decode('utf-8') + base64.b64encode(ct_bytes).decode('utf-8'))
```
输出结果为:
```
NDQyZTc1NjZiNDI4OTdkOA==Uw6t3RnJl1Dd5AzZkF9uJQ==
```
阅读全文