Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encryption and Decryption in Node.js

I am trying to encrypt and correspondingly decrypt a string.

When I am specifying the encoding scheme as 'utf-8', I am getting the results as expected :

    function encrypt(text) {
        var cipher = crypto.createCipher(algorithm, password)
        var crypted = cipher.update(text, 'utf8', 'hex')
        crypted += cipher.final('hex');
        return crypted;
    }

    function decrypt(text) {
        var decipher = crypto.createDecipher(algorithm, password)
        var dec = decipher.update(text, 'hex', 'utf8')
        dec += decipher.final('utf8');
        return dec;
    }

//text = 'The big brown fox jumps over the lazy dog.'  

Output : (utf-8 encoding)

enter image description here

But when I am trying to do it with 'base-64', its giving me unexpected results :

function encrypt(text) {
    var cipher = crypto.createCipher(algorithm, password)
    var crypted = cipher.update(text, 'base64', 'hex')
    crypted += cipher.final('hex');
    return crypted;
}

function decrypt(text) {
    var decipher = crypto.createDecipher(algorithm, password)
    var dec = decipher.update(text, 'hex', 'base64')
    dec += decipher.final('base64');
    return dec;
}

Output : (base-64 encoding)

enter image description here


I am unable to understand why base-64 encoding scheme is not accepting up the spaces and '.' in right format.
If someone know this, please help me out in getting a better understanding for this. Any help is appreciated.

like image 730
Prerna Jain Avatar asked Nov 09 '22 07:11

Prerna Jain


1 Answers

If I understand you correctly, you are calling both encrypt methods with the same string: The big brown fox jumps over the lazy dog.. Thing is, cipher.update's signature looks like this:

cipher.update(data[, input_encoding][, output_encoding])

So in the second encrypt method, you are using 'base64' as the input encoding. And your string is not base64 encoded. Base64 cannot have spaces, periods etc.

You probably want to encode it in base64 first. You can see the answers here to see how to do that: How to do Base64 encoding in node.js?

Then you can use your second encrypt method. After you decrypt it, you'll receive a base64 encoded string again, and you'll have to decode it. The question above also shows how to decode from base64.

like image 103
ralh Avatar answered Nov 15 '22 06:11

ralh