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

Time:01-30

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!

I expected it to output something like

U2FsdGVkX1  p462vXg3LggRE5kzRtX3VbKkcMBWuHY=

but it didn't work.

CodePudding user response:

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).

  • Related