[Python] 纯文本查看 复制代码
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()
[JavaScript] 纯文本查看 复制代码
const CryptoJS = require("crypto-js");
const fs = require("fs");
const testData = JSON.parse(fs.readFileSync("test_data.json", "utf-8"));
const encryptedBase64 = testData.encrypted;
const expectedPlaintext = testData.expected;
function decrypt(encryptedBase64) {
const SECRET_KEY = "16-bytesecretkey";
const IV_LENGTH = 16;
try {
const combined = CryptoJS.enc.Base64.parse(encryptedBase64);
const iv = CryptoJS.lib.WordArray.create(
combined.words.slice(0, IV_LENGTH / 4),
IV_LENGTH
);
const ciphertext = CryptoJS.lib.WordArray.create(
combined.words.slice(IV_LENGTH / 4),
combined.sigBytes - IV_LENGTH
);
const key = CryptoJS.enc.Utf8.parse(SECRET_KEY);
const decrypted = CryptoJS.AES.decrypt(
{ ciphertext: ciphertext },
key,
{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}
);
return decrypted.toString(CryptoJS.enc.Utf8);
} catch (e) {
console.error("解密失败:", e);
throw e;
}
}
try {
const decryptedText = decrypt(encryptedBase64);
if (decryptedText === expectedPlaintext) {
console.log(decryptedText);
process.exit(0);
} else {
console.error("解密结果不匹配");
console.error("期望:", expectedPlaintext);
console.error("实际:", decryptedText);
process.exit(1);
}
} catch (error) {
console.error("测试失败:", error);
process.exit(1);
}
我用python和js还原了一下,可以正常解密,但是如果SECRET_KEY是中文的话会报错。 |