How to decrypt AES with CryptoJS
Asked Answered
A

2

3

I'm trying for some time to decrypt a message in AES that use a Java app , but it never works . Can someone help me?

var options = { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 };  

        /*** encrypt */  
        var json = CryptoJS.AES.encrypt("Message", "KEY", options);  
        var ciphertext = json.ciphertext.toString(CryptoJS.enc.Base64);  
            console.log("chiper text ", ciphertext);

        /*** decrypt */  
        var decrypted = CryptoJS.AES.decrypt(json, "KEY", options);  
        var plaintext = decrypted.toString(CryptoJS.enc.Utf8);  
            console.log("decrypted ", plaintext);

But it is always generated a different ciphertext, never the same from my database.

Amerson answered 3/9, 2016 at 21:30 Comment(1)
Welcome to Stack Overflow! Since you haven't shown us the error and the Java code there could be any number of this wrong: wrong key, wrong encoding, incomplete/overfull ciphertext. You should show the encryption code and give the example values that you've used. Otherwise, it would be plain guessing what might be wrong with this code (or the encryption code). In short, please create a Minimal, Complete, and Verifiable example and edit your question to include it.Richert
P
15
var CryptoJS = require("crypto-js");

var key = CryptoJS.enc.Utf8.parse('b75524255a7f54d2726a951bb39204df');
var iv  = CryptoJS.enc.Utf8.parse('1583288699248111');
var text = "My Name Is Nghĩa";


var encryptedCP = CryptoJS.AES.encrypt(text, key, { iv: iv });
var decryptedWA = CryptoJS.AES.decrypt(encryptedCP, key, { iv: iv});
var cryptText = encryptedCP.toString();
console.log(cryptText);
console.log(decryptedWA.toString(CryptoJS.enc.Utf8));

//Decode from text    
var cipherParams = CryptoJS.lib.CipherParams.create({
     ciphertext: CryptoJS.enc.Base64.parse(cryptText )
});
var decryptedFromText = CryptoJS.AES.decrypt(cipherParams, key, { iv: iv});
console.log(decryptedFromText.toString(CryptoJS.enc.Utf8));
Proliferate answered 26/3, 2021 at 10:21 Comment(0)
G
5

try this to encrypt data

var data = CryptoJS.AES.encrypt(message, key);
data = data.toString()

then decrypt it like this

var decr = CryptoJS.AES.decrypt(data, key);
decr = decr.toString(CryptoJS.enc.Utf8);
Gassaway answered 3/9, 2016 at 22:3 Comment(2)
Please don't answer questions which are not yet fully defined. When/If the OP edits their question with the missing details, your answer will be obsolete and you get into the awkward position of still wanting to keep your answer, but at the expense of future readers who will be confused, because there is no direct connection between your answer and the question anymore.Richert
I got bit by the fact, tha you need to pass CryptoJS.enc.Utf8 when you decrypt. I spotted it thanks to this answer!Minimus

© 2022 - 2024 — McMap. All rights reserved.