我試圖加密服務器端(加密節點)和解密客戶端(CryptoJS)。我可以使用cryptoJS創建密鑰,並且可以在使用相同單獨的庫時進行加密和解密,但問題是我無法使用Crypto加密,而是使用CryptoJS進行解密,這是真實世界的場景。沒有錯誤,只是一個空的迴應。CryptoJS中加密解密的Javascript加密
任何幫助非常感謝請!
iv = crypto.randomBytes(16),
orig = 'A confidential message.';
//Crypto JS creates key
var password = "sixteen byte key";
var salt = CryptoJS.lib.WordArray.random(128/8);
var key = CryptoJS.PBKDF2(password, salt, { keySize: 128/32, iterations: 1000 });
console.log("step1 generated key: "+ key);
//Convert key for crypto use - as a Buffer
var hashHex = key.toString(CryptoJS.enc.Hex);
var hash = new Buffer(hashHex,'hex');
//Test encryption and decryption with crypto (Node)
//use CryptoJS key to encrypt data using crypto cipheriv
var cipher2 = crypto.createCipheriv('aes-128-cbc', hash, iv); //iv must be a buffer
var encrypted1 = cipher2.update(orig, 'utf8', 'hex');
var encrypted2 = encrypted1 += cipher2.final('hex');
console.log("Crypto string:", encrypted2.toString());
// Start decrypt
var decipher = crypto.createDecipheriv('aes-128-cbc', hash, iv);
var dec = decipher.update(encrypted2, 'hex', 'utf8')
dec += decipher.final('utf8');
console.log("Crypto decrypted msg:", dec);
//test with crypto JS (ie the client)
//CryptoJS key is a string
var encryptedCJS = CryptoJS.AES.encrypt(orig, key.toString(), { iv: iv, mode: CryptoJS.mode.CBC});
console.log("CryptoJS encrypted: "+encryptedCJS);
var decryptedCryptoJS = CryptoJS.AES.decrypt(encryptedCJS, key.toString(), { mode: CryptoJS.mode.CBC, iv: iv });
console.log("CryptoJS decrypted msg: "+decryptedCryptoJS.toString(CryptoJS.enc.Utf8));
//This part does not work - use message encrypted by crypto but cannot decrypt with CryptoJS. decryptedCryptoJSFinal is empty
var decryptedCryptoJSFinal = CryptoJS.AES.decrypt(encrypted2, key.toString(), {iv: iv, mode: CryptoJS.mode.CBC});
console.log("FINAL CryptoJS decrypted: "+decryptedCryptoJSFinal.toString(CryptoJS.enc.Utf8));
我認爲密碼加密的輸出必須是不同的格式才能輸出CryptoJS加密,但我找不到問題。總的來說,我打算髮送加密的數據作爲JSON在CryptoJS的客戶端上進行解密。
FWIW,如果您使用的WebPack/browserify /等您可以使用相同的節點'crypto' API。 – mscdex
@mscdex好點謝謝。 FWIW我想使用一個不同的lib,因爲服務器可能是Java,.Net等。順便說一句,我認爲我已經破解了它,CryptoJS希望解密一個「字數組」,所以我認爲問題在那裏。仍然證明在莫的修復。 – user7239926