Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Im trying to encrypt a string in javascript but it returns different strings

I’m trying to create a script that encrypts strings, here’s my code:

<!DOCTYPE html>
<html lang="nl">
    <head>
        <link rel="stylesheet" type="text/css" href="/denoryplay3/css/style.css">
        <title>Encryption</title>
    </head>
    <body>
        
        <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js" integrity="sha256-/H4YS+7aYb9kJ5OKhFYPUjSJdrtV6AeyJOtTkw6X72o=" crossorigin="anonymous"></script>

        <script>
        
        function encrypt(data, key){
            return CryptoJS.AES.encrypt(data, key);
        }
        function decrypt(data, key){
            
            return CryptoJS.AES.decrypt(data, key);
        }





        </script>
    </body>
</html>

And i tried running this code:

alert(decrypt(encrypt("hi", "12345"), '12345'));

, if you can understand it 😉 but it returned 6869, and i don’t understand why. Can someone pls help me? Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I expected it to output something like

U2FsdGVkX1++p462vXg3LggRE5kzRtX3VbKkcMBWuHY=

but it didn’t work.

>Solution :

The error is in the way you’re decrypting it. Please see the solution below.

function encrypt(data, key){
  return CryptoJS.AES.encrypt(data, key);
}
function decrypt(data, key){

  return CryptoJS.AES.decrypt(data, key);
}

var txt = "hi";
var key = "12345";

var encrypted = encrypt(txt,key).toString();
var decrypted = decrypt(encrypted,key).toString(CryptoJS.enc.Utf8);

console.log(encrypted,decrypted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js" integrity="sha256-/H4YS+7aYb9kJ5OKhFYPUjSJdrtV6AeyJOtTkw6X72o=" crossorigin="anonymous"></script>

Your decrypting needs to pass the CryptoJS.enc.Utf8 argument to .toString(), in order to specify the encoding of the decrypted text (which is UTF8, in our case).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading