base64 string gets written as an invalid image using Node.JS - javascript

I have the following code:
var __dirname = '/home/ubuntu/Site/public/uploads/';
var base64Data = '/9j/2wBDABAICAgICBAICAgQEBAQECAYEBAQECggIBggMCgwMDAoMDAwOEhAMDhIODAwQFhASFBQUFBQMEBYYFhQYEhQUFD/2wBDARAQEBAQECgYGChQODA4UFBQUFBQUFBQUA==UFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUP/AABEIADwAUAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQ==AwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eA==eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAw==BAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWVw==WFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQ==AxEAPwDmraLzIyTzkYINUby+njmEKtxH1HqeamkvXs7cxoPnPHPas4lyxZsknrUpGjZNJGsn7+2/4EvcUscjKMMKhViDkZqZJJnXaQSPcUwTAznOAKka2cJukxuPY06C3ELedA==oII+6PepA0074EW0E5x/n8qENu5Hb2zn5RkcGmeQ7zbCCMHmtKKMxuFHPBAPv6/zpJIgX4x+P+f85HpTTFYksFEafLxgdv8AP+fwp5k/doxYfLxz7f5J/P1pbYbUbn8cf59/1g==oYpMxMgP3T1/l/LNMogmt4rsHHUn+p/+tVY6W45DZHfj/PvU43xNkHIB/wA/y/WrEFwrDa/p/TH9Ki5NrlEWnlnLLx/F7f55/Kp7dEbnAwf8/wBTWi1vFOPl55/r/wDX/Wqktg==zQsWA6/eGev+fmoHYfbLHLHiQAsDwD74/wDZiPwBpXRcAx5x/D/T8hg/U1HauXmZF6nt/tf/AK2/SppkJTbGPvfd+nX+QX86ABVV2Mijj7q+4/8Arnim4+bcT+J/n/n1PpU6wA==dm0L7Y/p+v8A49TTCVO4n8f1z/X8TQMVflU9vr/n2x+HvWdJI8E5ZD9Rj/Pt+dX3YKMAdPX/AD+FULv7xYVQE5iOOR/niozCycjt/n+lS22oW8y4Zh0/oP8ACrIiikPB7/1NQA==FWG4kh4z/n/IFXkmiuVKsoOT3Hvj+oqBrX5dw9M/oDUW2WE/Ken/ANf/AAoAnayAkE9vJg+/Uf49f19qvaZZG/Mrx4jaJARHI3Xnt+QH4VRS5BHJ9v5/4ile7bAuIcEo3KH+JQ==PUfy/M0ATyh4hg8jGAPUf/q4+v0qB5SwLMR/j/n/ANmqeS8jZN5YYI6/1/kfxNZ9zdITiPgUDCabPGaqyupB5FJLN71VmmJ71SAhjWVT8oNXrO8uoiMgkA1TYlD8pNPjkc8ZpA==QjTXU224x2x+hFObUVY/Mnf+v/16zS7DvTSzY60Fl57xRjDAdP6f4U2K8BDKH49/pWc8jZojkbJ5osFy1Nc+SxMTkgnlaYb3PIFMVRK3zGnyWsUZUjPLYOTTsK5G1wzUxydhNQ==NNDHGDtFRFR5LH0xTE2f/9k=';
var buffer = new Buffer(base64Data, 'base64');
fs.writeFileSync(__dirname + 'zorro.jpg', buffer, 0, buffer.length);
However the saved image is corrupt and won't open in Finder. What am I doing wrong? Am I missing some header? The base64 string opens perfectly fine as inline data with an img tag.
EDIT: this works in HTML for me:
<img src="data:image/jpg;base64,/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/AK2/SppkJTbGPvfd+nX+
QX86ABVV2Mijj7q+4/8Arnim4+bcT+J/n/n1PpU6wHZtC+2P6fr/AOPU0wlTuJ/H9c/1/E0DFX5V
Pb6/59sfh71nSSPBOWQ/UY/z7fnV92CjAHT1/wA/hVC7+8WFUBOYjjkf54qMwsnI7f5/pUttqFvM
uGYdP6D/AAqyIopDwe/9TUAVYbiSHjP+f8gVeSaK5Uqyg5Pce+P6ioGtfl3D0z+gNRbZYT8p6f8A
1/8ACgCdrICQT28mD79R/j1/X2q9plkb8yvHiNokBEcjdee35AfhVFLkEcn2/n/iKV7tsC4hwSjc
of4lPUfy/M0ATyh4hg8jGAPUf/q4+v0qB5SwLMR/j/n/ANmqeS8jZN5YYI6/1/kfxNZ9zdITiPgU
DCabPGaqyupB5FJLN71VmmJ71SAhjWVT8oNXrO8uoiMgkA1TYlD8pNPjkc8ZpEI011NtuMdsfoRT
m1FWPzJ3/r/9es0uw700s2OtBZee8UYwwHT+n+FNivAQyh+Pf6VnPI2aI5GyeaLBctTXPksTE5IJ
5WmG9zyBTFUSt8xp8lrFGVIzy2Dk07CuRtcM1McnYTU00McYO0VEVHksfTFMTZ//2Q==
As to why the base64 encoded data is working on my end, the RFC4648 for base64 states this:
Furthermore, such specifications MAY ignore the pad character, "=",
treating it as non-alphabet data, if it is present before the end
of the encoded data. If more than the allowed number of pad
characters is found at the end of the string (e.g., a base 64
string terminated with "==="), the excess pad characters MAY also be
ignored.
Some implementation will ignore the added "=" and some will not.
EDIT:
As other has pointed out, your base64 string seems to be many base64 string concatenated together. Here is your string:
/9j/2wBDABAICAgICBAICAgQEBAQECAYEBAQECggIBggMCgwMDAoMDAwOEhAMDhIODAwQFhASFBQUFBQMEBYYFhQYEhQUFD/2wBDARAQEBAQECgYGChQODA4UFBQUFBQUFBQUA==
UFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUP/AABEIADwAUAMBIgACEQEDEQH/xAAfAAABBQEBAQEBA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nX+QX86ABVV2Mijj7q+4/8Arnim4+bcT+J/n/n1PpU6wA==
dm0L7Y/p+v8A49TTCVO4n8f1z/X8TQMVflU9vr/n2x+HvWdJI8E5ZD9Rj/Pt+dX3YKMAdPX/AD+FULv7xYVQE5iOOR/niozCycjt/n+lS22oW8y4Zh0/oP8ACrIiikPB7/1NQA==
FWG4kh4z/n/IFXkmiuVKsoOT3Hvj+oqBrX5dw9M/oDUW2WE/Ken/ANf/AAoAnayAkE9vJg+/Uf49f19qvaZZG/Mrx4jaJARHI3Xnt+QH4VRS5BHJ9v5/4ile7bAuIcEo3KH+JQ==
PUfy/M0ATyh4hg8jGAPUf/q4+v0qB5SwLMR/j/n/ANmqeS8jZN5YYI6/1/kfxNZ9zdITiPgUDCabPGaqyupB5FJLN71VmmJ71SAhjWVT8oNXrO8uoiMgkA1TYlD8pNPjkc8ZpA==
QjTXU224x2x+hFObUVY/Mnf+v/16zS7DvTSzY60Fl57xRjDAdP6f4U2K8BDKH49/pWc8jZojkbJ5osFy1Nc+SxMTkgnlaYb3PIFMVRK3zGnyWsUZUjPLYOTTsK5G1wzUxydhNQ==
NNDHGDtFRFR5LH0xTE2f/9k=
Notice how each of base64 string are 136 chracter long. If you decoded each of these base64 and append the result of each decoded base64 into a file, you will get your image.

Related

Obtaining same Base64 encoded output of encrypted string in Java and JavaScript

After getting byte array encryptedMessageInBytes from AES encryption function call cipher.doFinal in Java, I convert the byte array to base64 like this:
String encryptedMessageInBase64 = new String(Base64.getEncoder().encode(encryptedMessageInBytes));
In JavaScript, I simply do .toString() to the output I get from CryptoJS.AES.encrypt method and I get exact same base64 string. i.e.
var encryptedMessageInBase64 = CryptoJS.AES.encrypt("Message", "Secret Passphrase").toString();
It gives same base64 string as in Java code.
However, in one of the Java source code, they have done like this:
String encryptedMessageInBase64 = Base64.getUrlEncoder().encodeToString(encryptedMessageInBytes);
What shall I do in JavaScript to obtain same base64 string?
Here is answer:
However, in one of the Java source code, they have done like this:
String encryptedMessageInBase64 = Base64.getUrlEncoder().encodeToString(encryptedMessageInBytes);*
Here, basically they have done UrlEncoding instead of Base64 encoding. It is nothing but replacing + and / characters with - and _ characters. Url encoding is when we want to send encoded string over HTTP where it treats these two as special characters this is why we need to replace them with some other characters which are HTTP friendly.

Encode in Java and Decode in Javascript

I want to pass a Base64 Image to the front end in a parameter.
I tried to send normal Base64 but it was giving me an error, probably because of the special characters in the Base64 Image.
So I tried in Java:
String base64Signature = Base64.getEncoder().encodeToString(image); // Encode to base64
return URLEncoder.encode(base64Signature, "utf-8"); // This class contains static methods for converting a String to the application/x-www-form-urlencoded MIMEformat
And in Javascript data.Signature has the image data. Neither
vm.Signature = data.Signature;
or
vm.Signature = decodeURIComponent(data.Signature);
worked. I copied the image data String in a online converter and it didn't display anything.
How should I do this?
The problem could be that Java's URLEncoder encodes spaces as + signs and JavaScript's decoder expects spaces as %20s. You can try replacing the + signs, for example:
decodeURIComponent(data.Signature.replace(/\+/g, '%20'));

How to remove illegal characters from nodejs buffer?

I got a base64 encoded string of a csv file from frontend. In backend i am converting base64 string to binary and then trying to convert it to json object.
var csvDcaData = new Buffer(source, 'base64').toString('binary')//convert base64 to binary
Problem is, Ui is sending some illegal characters with on of the field which are not visible to user in plain csv. "" these are characters appended in one of csv field.
I want to remove these kind of characters from data from base64 but i am not able to recognize them in buffer, after conversion these characters appear.
It is possible in any way to detect such kind of characters from buffer.
The source is sending you a message. The message consists of metadata and text. The first few bytes of the message are identifiable as metadata because they are the Byte-Order Mark (BOM) encoded in UTF-8. That strongly suggests that the text is encoded in UTF-8. Nonetheless, to read the text you should find out from the sender which encoding is used.
Yes, the BOM "characters" should be stripped off when wanting to deal only in the text. They are not characters in the sense that they are not part of the text. (Though, if you decode the bytes as UTF-8, it matches the codepoint U+FEFF.)
So, though perhaps esoteric, the message does not contain illegal characters but actually has useful metadata.
Also, given that you are not stripping off the BOM, the fact that you are seeing "" instead of "" (U+FEFF ZERO WIDTH NO-BREAK SPACE) means that you are not using UTF-8 to decode the text. That could result in data loss. There is no text but encoded text. You always have to know and use the correct encoding.
Now, source is a JavaScript string (which, by-the-way, uses the UTF-16 encoding of Unicode). The content of the string is a message encoded in Base64. The message is a sequence of bytes which are the UTF-8 encoding of a BOM and text. You want the text in a JavaScript string. (And the text happens to be some form of CSV. For that, you'll need to know the line ending, delimiter, and text-qualifier.) There is a lot for you and the sender to talk about. Perhaps the sender has documented all this.
const stripBom = require('strip-bom');
const original = "¡You win one million ₹! Now you can get a real 🚲";
const base64String = Buffer.from("\u{FEFF}" + original, "utf-8").toString("base64");
console.log(base64String);
const decodedString =
stripBom(Buffer.from(base64String, "base64").toString("utf-8"));
console.log(decodedString);
console.log(original === decodedString);

base64 encoding in javascript decoding in php

I am trying to encode a string in javascript and decode it in php.
I use this code to put the string in a inputbox and then send it via form PUT.
document.getElementById('signature').value= b64EncodeUnicode(ab2str(signature));
And this code to decode
$signature=base64_decode($signature);
Here there is a jsfiddle for the encoding page:
https://jsfiddle.net/okaea662/
The problem is that I always get a string 98% correct but with some different characters.
For example: (the first string is the string printed in the inputbox)
¦S÷ä½m0×C|u>£áWÅàUù»¥ïs7Dþ1Ji%ýÊ{\ö°(úýýÁñxçO9Ù¡ö}XÇIWçβÆü8ú²ðÑOA¤nì6S+̽ i¼?¼ºNËÒo·a©8»eO|PPþBE=HèÑqaX©$Ì磰©b2(Ðç.$nÈR,ä_OX¾xè¥3éÂòkå¾ N,sáW§ÝáV:ö~Å×à<4)íÇKo¡L¤<Í»äA(!xón#WÙÕGù¾g!)ùC)]Q(*}?­Ìp
¦S÷ ä½m0×C|u>£áWÅàUù»¥ïs7Dþ1Ji%ýÊ{\ö°(úýýÁñxçO9Ù¡ö}XÇIWçβÆü8ú²ðÑOA¤nì6S+̽ i¼?¼ºNËÒo·a©8»eO|PPþBE=HèÑ qaX©$Ì磰©b2(Ðç.$nÈR,ä_OX¾xè¥3éÂòkå¾ N ,sá W§ÝáV:ö~Å×à<4)íÇKo¡L¤<Í»äA(!xón#WÙÕGù¾g!)ùC)]Q(*}?­Ìp
Note that the 4th character is distinct and then there is one or two more somewhere.
The string corresponds to a digital signature so these characters make the signature to be invalid.
I have no idea what is happening here. Any idea? I use Chrome browser and utf-8 encoding in header and metas (Firefox seems to use a different encoding in the inputbox but I will look that problem later)
EDIT:
The encoding to base64 apparently is not the problem. The base64 encoded string is the same in the browser than in the server. If I base64-decode it in javascript I get the original string but if I decode it in PHP I get a slightly different string.
EDIT2:
I still don't know what the problem is but I have avoided it sending the data in a blob with ajax.
Try using this command to encode your string with js:
var signature = document.getElementById('signature');
var base64 = window.btoa(signature);
Now with php, you simply use: base64_decode($signature)
If that doesn't work (I haven't tested it) there may be something wrong with the btoa func. So checkout this link here:
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
There is a function in there that should work (if the above does not)
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode(signature); // "4pyTIMOgIGxhIG1vZGU="

Error in displaying base64 encoded string as image in browser?

I am working on a website for a friend which takes in a signature from a wacom STU-300 signature tablet, to then be placed in the database. (as any data type as long it is readable, I tried BLOB and varchar). After checking the documentation I found out that there is a method where you can retrieve the data as a base64 encoded string after taking the signature. This is an example I printed from a signature after extracting the base64 encoded string:
"RlP5QhsBHAECGUVDFxYZVCQFBwkDBggLBA0MFB0cGhsYFTgCIgUgJx3EG8LuM6ZpqwR8ScEztVwTqbxuB8+gFfRUzHv7lXdFA46EAUMBARcEA1dITxYCASAZIgQgcKIShjL9FJx63Xpnkli3HoFMatdpMwfX7Bg528NKz2JUAgE0JAEBBQoBBQCsTaD5BQIABwoBBQDEE/mABgIBCQgBBQAAkE4EAAMJAmABCAIDXQAQBmcCYOIfBghgkBgoNERQYGhsdISAmJyktLCsoJSMeHBMMAvrz7egHl/5+gHs97/Dy8wvQP128/Lv6+jk3tzX1NEHQ+09jcB3/eDb2tcHVo2OHr+QgYKj5QX212fH17cGZURTYvHx4V/ACGoCYMMHCAhj/QkNEBIBF/QZFBMNBwP9+PPs497WAdO90tPX2drb2Nvf5u/4AAkSHiYxNz5FTVRXVVFQTkxKRkRHRkVCPzsxJRMF+Onc0MjBvLe5vcDCv73BydXl9QQTHicwNDcBNv01Nz49CwfIAQABAQEABAkCYAEIAQNdAEANYAJgYQUIWqA4UGh4kIiAYEgwKCAYgIAGICCA/AgMIEIB8BgoQEH4CgQCAAJP8AAH/yAf4EBgIAA/4gIH6H879gAKBhAgfof73+AgYQTwGCgggUIFv//Pr38/IPf3j0rWYAwIAQUA/wMAAAAUCAEEAKxNAMQTHQ8OBjAQs9uhtgasnhcBsPYcKypNaWNyb3NvZnQ7J1dpbmRvd3MgOCsnOyh1bmtub3duKTs7Ni4zLjk2MDAaFhVTVFU7J1NUVS0zMDAnOzEuMC44OzAbCQgwMDU3O1NUVRgHjJfKqQXgARUKAQTqA+k7tw23DTgBBA=="
Edit: Thanks vjdhama for removing the spaces now it does come up as a valid base64 string however I am still not able to convert this back into an image file. When I tried decoding this back into an image using the base64 decoder at WUtils, it comes up as
FS�BECT$
8" '���3�i�|I�3�\��nϠ�T�{��wE��CWHO " p��2��z�zg�X��Lj�i3��9��J�bT4$
instead of an image. I need to display the base64 encoded string in image form in the browser with php .
To check for validity of string we could use this regex
var base64 = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})([=]{1,2})?$");
Just test your string by
base64.test(str);
You can read more here : RegEx to parse or validate Base64 data
UPDATE:
You can also decode data using window.atob(str) web api method.
You can read more it here : https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/atob
Refer this for more on base64 encoding and decoding : https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

Categories