Search code examples
cryptojs

How can i use cryptojs in Native JS?


I'm using cryptoJs in NativeJS which is in html. but when i decript the txt with aesDecrypt(decrypted,key) and it won't work. i have tried many other Ciphers, and it still don't work. would you guys view the code below and give me some advice ?

I tried many Ciphers(like aes-192-ecb,aes-256-ecb) in backend and it stil don't work. It report : bad encrypt Error.

Front code: encrypt the txt and send to backend.
function aesEncrypt(data, key) {    
    key = CryptoJS.enc.Utf8.parse(key);    
    let encrypted = CryptoJS.AES.encrypt(data, key, {    
        mode: CryptoJS.mode.ECB,    
        padding: CryptoJS.pad.Pkcs7    
    });    
    return encrypted.toString();    
}   

Backend code: decrypt the txt sent from front.
function aesDecrypt(encrypted, key) {    
    const decipher = crypto.createDecipher('aes192', key);    
    let decrypted = decipher.update(encrypted, 'binary', 'utf8');    
    decrypted += decipher.final('utf8');    
    return decrypted;    
}

Solution

  • looks like i used wrong methods both front and backend.

    front code:
    <script src="https://cdn.jsdelivr.net/npm/crypto-js@3.1.9-1/crypto-js.js"></script>
    let encrypted = CryptoJS.AES.encrypt("txt", "Secret Passphrase").toString();
    
    
    backend code:
    const cryptojs = require("crypto-js");
    let txt = cryptojs.AES.decrypt(encrypted , "Secret Passphrase").toString(cryptojs.enc.Utf8);