我在Python中使用此方法编码了一个字符串。我想使用Javascript解码编码的字符串。
from Crypto.Cipher import XOR
def encrypt(key, plaintext):
cipher = XOR.new(key)
return base64.b64encode(cipher.encrypt(plaintext))
我得到了一个更好的解决方案,可以用Python加密,用Javascript解密。
Python编码部分:
import base64
from Crypto import Random
from Crypto.Cipher import AES
import json
def encrypt_val(clear_text):
master_key = '0123456789101112'
encoder = PKCS7Encoder()
raw = encoder.encode(clear_text)
iv = Random.new().read( 16 )
cipher = AES.new( master_key, AES.MODE_CBC, iv, segment_size=128 )
return base64.b64encode( iv + cipher.encrypt( raw ) )
print(encrypt_val(json.dumps({"name":"Tahir"})))
Javascript解码部分:
const CryptoJS = require('crypto-js')
const atob = require('atob')
function decryptMsg (data) {
master_key = '0123456789101112';
// Decode the base64 data so we can separate iv and crypt text.
var rawData = atob(data);
// Split by 16 because my IV size
var iv = rawData.substring(0, 16);
var crypttext = rawData.substring(16);
//Parsers
crypttext = CryptoJS.enc.Latin1.parse(crypttext);
iv = CryptoJS.enc.Latin1.parse(iv);
key = CryptoJS.enc.Utf8.parse(master_key);
// Decrypt
var plaintextArray = CryptoJS.AES.decrypt(
{ ciphertext: crypttext},
key,
{iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7}
);
// Can be Utf8 too
output_plaintext = CryptoJS.enc.Latin1.stringify(plaintextArray);
console.log("plain text : " + output_plaintext);
}
encoded_message = "XF8T/miPPVk9B7GfNUshRqJf6//sJnWey+TqoXj70Tp0vJhjw22uDLOLh7es4BOp"
decryptMsg(encoded_message)