Encryption and Decryption in Node.js

I am trying to encrypt and decrypt a string accordingly.

When I specify the encoding scheme as " utf-8 ", I get 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 try to do it with base-64 it gives 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 can't figure out why the base-64 encoding scheme doesn't accept spaces and ".". in the correct format.
If anyone knows this please help me understand this better. Any help is appreciated.

+3


source to share


1 answer


If you have understood correctly, you are calling both the encryption method with the same line: The big brown fox jumps over the lazy dog.

. Thing, the signature cipher.update

looks like this:

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

So, in the second encryption method, you use it 'base64'

as the input encoding. And your string is not base64 encoded. Base64 cannot have spaces, periods, etc.



Most likely you need to base64 encode it first. You can see the answers here to see how to do this: How to do Base64 encoding in node.js?

Then you can use your second encryption method. After you decode it, you get the base64 encoded string again and you have to decode it. The above question also shows how to decode from base64.

+1


source







All Articles