import
base64
from
Crypto.Cipher
import
AES
from
Crypto.Util.Padding
import
pad
from
Crypto
import
Random
import
subprocess
import
json
import
os
SECRET_KEY
=
"16-bytesecretkey"
.encode(
'utf-8'
)
IV_LENGTH
=
16
def
encrypt(plaintext):
iv
=
Random.new().read(IV_LENGTH)
cipher
=
AES.new(SECRET_KEY, AES.MODE_CBC, iv)
padded_data
=
pad(plaintext.encode(
'utf-8'
), AES.block_size)
encrypted
=
cipher.encrypt(padded_data)
combined
=
iv
+
encrypted
return
base64.b64encode(combined).decode(
'utf-8'
)
def
test_decryption(encrypted_base64, expected_plaintext):
test_data
=
{
"encrypted"
: encrypted_base64,
"expected"
: expected_plaintext
}
with
open
(
'test_data.json'
,
'w'
, encoding
=
'utf-8'
) as f:
json.dump(test_data, f, ensure_ascii
=
False
)
result
=
subprocess.run(
[
'node'
,
'test_decrypt.js'
],
capture_output
=
True
,
text
=
True
)
if
result.returncode
=
=
0
:
print
(
"✅ 测试通过: JS解密成功"
)
print
(f
"原始文本: {expected_plaintext}"
)
print
(f
"解密结果: {result.stdout.strip()}"
)
else
:
print
(
"❌ 测试失败: JS解密出错"
)
print
(
"错误信息:"
)
print
(result.stderr)
def
main():
print
(
"🔐 AES解密功能验证工具"
)
print
(
"="
*
50
)
test_cases
=
[
(
"Hello World!"
,
"短文本测试"
),
(
"Python验证前端JS解密功能"
,
"中文测试"
),
(
"A"
*
100
,
"长文本测试"
),
(
"特殊字符测试: !@#$%^&*()_+-=[]{}|;:,.<>?/"
,
"特殊字符"
)
]
for
plaintext, description
in
test_cases:
print
(f
"\n🔧 测试用例: {description}"
)
print
(f
"原始文本: {plaintext}"
)
encrypted_base64
=
encrypt(plaintext)
print
(f
"加密结果: {encrypted_base64[:30]}... (Base64)"
)
test_decryption(encrypted_base64, plaintext)
if
os.path.exists(
'test_data.json'
):
os.remove(
'test_data.json'
)
if
__name__
=
=
"__main__"
:
main()