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)
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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With