Base64 encoding of String in Node.js - javascript

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==

Related

Encoding and Decoding in Node js

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

encrypt href link in url using javascript

file:///C:/xx/xx/xx/xx/xx/xx/studentInfo.html
I want to encrypt the studentInfo.html into characters like for example
file:///C:/xx/xx/xx/xx/xx/xx/A%1fs%fdd.html
using javascript? How can I do this?
You could encode it in Base64 with with the atob() (decode) and btoa() (encode) javascript fonctions.
var path = "file:///C:/xx/xx/xx/xx/xx/xx/"
var file = "studentInfo.html"
console.log(path + btoa(file))
// Output: file:///C:/xx/xx/xx/xx/xx/xx/c3R1ZGVudEluZm8uaHRtbA==

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));

How to get image from the page and store in variable via jQuery?

img src="~/Images/Barcodes/MGRNNo.jpg" id="barCodeImage" width="150px" height="60"
I want to store the above image in variable via jQuery
like
var barcodeimage=$('#barCodeImage').image();
and
I want to print it
like
applet.append64(barcodeimage);
applet.print();
Is it possible ?
As I can see based on your example code I suspect that you want to have the base64 code of the image right?
Anyways, What you can do is get the outerHTML of the <img> object and encode that as a base64 string. In the end you can use the base64 string to decode it:
// get object
var barcodeimage = $( "#test" )[ 0 ].outerHTML;
console.log(barcodeimage);
// Encode the String
var encodedString = btoa(barcodeimage);
console.log(encodedString);
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://blog.stackoverflow.com/images/wordpress/stackoverflow-logo-300.png" id="test"></img>
The btoa() method encodes a string in base-64. Use the atob() method to decode a base-64 encoded string.

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).

Categories

Resources