Search code examples
javascriptencryptionencodingaescryptojs

Need help decrypting an AES encrypted string with Javascript (using crypto-js)


I found that someone had written a demo page that encrypts data on the client side with CryptoJS, which is here:

https://github.com/odedhb/AES-encrypt

It only has an encrypt function, so I added what I thought would be a decrypt function but end up with completely different text as a result.

My entire test page:

<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>

<br>text:<input id='text' type='text' value='0.1'/>

<br>password:<input id='pass' type='text' value='cool'/>

<br><button onclick="encrypt()">encrypt</button>
<br><button onclick="decrypt()">decrypt</button>


<br>encrypted:<br><input id='result'></input>


<br>decrypted:<br><span id="decode"></span>

<script>
    function encrypt(){

        var encrypted = CryptoJS.AES.encrypt(document.getElementById("text").value, document.getElementById("pass").value);
        document.getElementById("result").value = encrypted;
    }

    function decrypt(){

        var decrypted = CryptoJS.AES.decrypt(document.getElementById("result").value, document.getElementById("pass").value);
        document.getElementById("decode").innerHTML = decrypted;
    }

</script>

</html>

On this page, if I enter Hi I'm Lucas as the plaintext (no quotes), with a password of passwd, I receive back a string of this: U2FsdGVkX1/S3TobCOdyJ7k7eaBhdFKRpJkDBTpV1D0=

If i go on to click the decrypt button, I don't get any errors, but i just get a result of 48692049276d204c75636173.

Obviously, I've done something wrong, and am hoping for an assist here :)


Solution

  • From this, it seems the following should work:

    document.getElementById("decode").innerHTML = decrypted.toString(CryptoJS.enc.Utf8)