Encoding and Decoding in Node js - javascript

I have a string, On which I need to encode it into "iso-8859-1" and then I need to convert back it into a readable string.
Is there any way to do this in node js natively? If I am encoding it into "iso-8859-1" then do I need to use the same to decode it back?
I am able to do it in .Net
string encodedData = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); // encoding in "iso-8859-1"
byte[] = decodedbuff = convert.FromBase64String(encodedData); // getting buffer
result = encoding.GetString(decodedbuff); //decoding
How to achieve it in node js?

You can simply create a buffer from your encoded base64 string and then use toString() with latin1 (iso-8859-1 is latin1 in nodejs) on the buffer to get the decoded string:
const encoded = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
const buffer = Buffer.from(encoded, 'base64');
console.log(buffer.toString('latin1')); // prints T i m e s e r e i s

Related

convert base64 string to csv javascript giving blob error

I am simply trying to convert a base-64 string to csv. The file is in CSV format transmitted in base-64 string.
I am implementing this in Microsoft Office Excel Addins
Code base-64-string
// getting the base-64 string
let base_64_string = [base-64-string];
// decode the base-64 string
let csvContent = atob(base_64_string);
// convert the decoded base-64 string to csv
var blob = new Blob([csvContent], {type: "data:application/octet-stream;base64"});
Error
Compiled with problems:
WARNING in ./src/taskpane/taskpane.js 310:17-21
export 'Blob' (imported as 'Blob') was not found in 'buffer' (possible exports: Buffer, INSPECT_MAX_BYTES, SlowBuffer, kMaxLength)
Another method here
The code you've posted is not the problem (as demonstrated by the code snippet below).
// generate a base-64 encoded csv string
const base_64_string = btoa("a,b,c");
// decode the base-64 string
const csvContent = atob(base_64_string);
// convert the decoded base-64 string to csv
const blob = new Blob([csvContent], {type: "data:application/octet-stream;base64"});
console.log(blob);

Convert a file from to Base 64 using JavaScript and converting it back to file using C#

I am trying to convert pdf and image files to base 64 using javascript and convert it back to file using C# in WEB API.
Javascript
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textAreaFileContents = document.getElementById("textAreaFileContents");
textAreaFileContents.innerHTML = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
C#
Byte[] bytes = Convert.FromBase64String(dd[0].Image_base64Url);
File.WriteAllBytes(actualSavePath,bytes);
But in API I'm getting exception as {"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "}
Please tell me how to proceed with this...
Thanks
According to MDN: FileReader.readAsDataURL those generated URLs are prefixed with something like data:image/jpeg;base64,. Have a look at your generated string. Look for the occurence of base64, and take the base64 data that starts after this prefix.
Because the FileReader.readAsDataURL() produces a string that is prefixed with extra metadata (the "URL" portion), you need to strip it off on the C# side. Here's some sample code:
// Sample string from FileReader.readAsDataURL()
var base64 = "data:image/jpeg;base64,ba9867b6a86ba86b6a6ab6abaa====";
// Some known piece of information that will be in the above string
const string identifier = ";base64,";
// Find where it exists in the input string
var dataIndex = base64.IndexOf(identifier);
// Take the portion after this identifier; that's the real base-64 portion
var cleaned = base64.Substring(dataIndex + identifier.Length);
// Get the bytes
var bytes = Convert.FromBase64String(cleaned);
You could condense this down if it's too verbose, I just wanted to explain it step by step.
var bytes = Convert.FromBase64String(base64.Substring(base64.IndexOf(";base64,") + 8));

Base64 encoding of String in Node.js

I try to encode a string in both browser and server but I have different base64 encoding for a specific string
Here is my string: "£aº©S=³hPó c¨¸" (Hexa: 00a3006100ba00a900940053003d00b30068005000f300900020006300a800b8 )
Client-side: I encode this String using btoa() and I have : o2G6qZRTPbNoUPOQIGOouA== and this is the result I expect.
Server-side: I code this String using Buffer according to this answer in Node.js i have :
var ciphertext = ... // myString
console.log(ciphertext.hexEncode()); // 00a3006100ba00a900940053003d00b30068005000f300900020006300a800b8
console.log(Buffer.from(ciphertext, 'utf8').toString('base64')) // wqNhwrrCqcKUUz3Cs2hQw7PCkCBjwqjCuA==
console.log(Buffer.from(ciphertext, 'ucs2').toString('base64')) // owBhALoAqQCUAFMAPQCzAGgAUADzAJAAIABjAKgAuAA=
I managed to obtain the base64 encoding I expect using the node-package base-64
I still don't know why, so if someone has a clue
var base64 = require('base-64');
var ciphertext = ...; //myString
var encoded = base64.encode(bytes);
console.log(encoded); // o2G6qZRTPbNoUPOQIGOouA==

CryptoJS not decrypting non-Latin characters faithfully

I am trying to use CryptoJS AES, like so:
var msg = "café";
var key = "something";
var c = CryptoJS.AES.encrypt(msg, key).toString();
CryptoJS.AES.decrypt(c, key).toString(CryptoJS.enc.Latin1);
Unfortunately this returns café, not café. Clearly Latin1 is not the right encoding to use, but I can't find a better one. Is there a solution?
Thanks.
You are just missing the format
The proper way is using CryptoJS.enc.Utf8
So, Please try:
CryptoJS.AES.decrypt(c, key).toString(CryptoJS.enc.Utf8);
https://code.google.com/p/crypto-js/#The_Hasher_Input
The hash algorithms accept either strings or instances of CryptoJS.lib.WordArray [...] an array of 32-bit words. When you pass a string, it's automatically converted to a WordArray encoded as UTF-8.
So, when you pass a string (and don't use CryptoJS.enc.* to generate a WordArray) it automatically converts the string (message) to a utf8 WordArray.
See here for sample roundtrip encrypt/decrypt:
https://code.google.com/p/crypto-js/#The_Cipher_Output
Here's a jsfiddle to play with CryptoJS
https://jsfiddle.net/8qbf4746/4/
var message = "café";
var key = "something";
var encrypted = CryptoJS.AES.encrypt(message, key);
//equivalent to CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(message), key);
var decrypted = CryptoJS.AES.decrypt(encrypted, key);
$('#1').text("Encrypted: "+encrypted);
$('#2').text("Decrypted: "+decrypted.toString(CryptoJS.enc.Utf8));
To emphasize my point here is the same thing using Latin1 encoding:
https://jsfiddle.net/3a8tf48f/2/
var message = "café";
var key = "something";
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Latin1.parse(message), key);
var decrypted = CryptoJS.AES.decrypt(encrypted, key);
$('#1').text("Encrypted: " + encrypted);
$('#2').text("Decrypted: " + decrypted.toString(CryptoJS.enc.Latin1));
On a side note, the API would probably be better if it only accepted WordArray and didn't overload the toString method (which is just a convenience interface to CryptoJS.enc.*.stringify). The string conversion magic is a little misleading.
You are trying to decrypt your data as a Latin1 string, even though your input string is not in Latin1. The encoding used by CryptoJS internally is not the same as the encoding you use to write the input file.
You need to specify the same encoding both when encrypting (for the string -> byte array conversion) and when decrypting (for the byte array -> string conversion).

MD5.ComputeHash(Encoding.Unicode.GetBytes(value)) into javascript

I need to translate the line below from vb.net to javascript
MD5.ComputeHash(Encoding.Unicode.GetBytes(value))
Im trying to use CryptoJS but I get diffrent results as I need to pass a string into that but a byte array into the MD5 function in VB.net
Can anyone help?
Thank you
Encoding.Unicode is a (misleading) name used by Windows for the UTF-16LE encoding.
However the CryptoJS functions, when given a string, encode it to bytes using the (more common) UTF-8, not UTF-16LE:
The hash algorithms accept either strings or instances of CryptoJS.lib.WordArray. A WordArray object represents an array of 32-bit words. When you pass a string, it's automatically converted to a WordArray encoded as UTF-8.
So you will need to create a WordArray from the string yourself before passing it in to MD5. With a new enough CryptoJS there's a function to do that for you:
CryptoJS.MD5(CryptoJS.enc.Utf16LE.parse(str))
IN C#:
var data = md5.ComputeHash(Encoding.Default.GetBytes(password));
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++) {
stringBuilder.Append(data[i].ToString("x2"));
}
return stringBuilder.ToString();
In Node.js
const crypto = require('crypto');
crypto.createHash('md5').update(value).digest('hex');

Categories

Resources