Encode and Decode base 64 in Node JS - arrays

I have a node JS program to concat a String to an encrypted message and base-64 encoding it. in my server program when I tried to base-64 decode, i am not getting the originally generated encrypted message.
i have replicated that problem in simple program below.
In this program,
I pass an encrypted and base 64 encoded message,
decode them, concatenating another string
encode the finalMessage
decode the finalMessage
Split them to get the encrypted message
encode the encrypted message to compare with original message.
the Result is - the original message passed to this function is not the same as the final message.
function decodeAndEncode(message) {
console.log("message---"+message)
const buffer = Buffer.from(message, 'base64');
console.log("buffer---"+buffer)
const updatedStringBuffer = Buffer.from('648f3ec157637553f170bccfe56bc32058d11741d016bf120e7001148b19a4d1');
const finalEncodedMsg = Buffer.from(updatedStringBuffer+"|"+buffer).toString('base64')
console.log("updatedMessage ---"+finalEncodedMsg);
const updatedMessageBuffer = Buffer.from(finalEncodedMsg, 'base64');
console.log("updatedMessageBuffer ---"+updatedMessageBuffer);
const getBackOriginalMsg = updatedMessageBuffer.toString('utf-8',updatedStringBuffer.length+1);
console.log("getBackOriginalMsg---"+getBackOriginalMsg);
const encodedMessageBack = Buffer.from(getBackOriginalMsg).toString('base64')
console.log("encodedMessageBack--- "+encodedMessageBack)
}
const message = 'KCof0N56Z0X5piDvPO4FRL6e80oOxxPzzTMie+QRUy00RzwBn1qubNTtt8z5J+LykqlbcWSWfjGarNr4c40I+RdrI+Fi1r/wCs2ql0kvYYapTaaz9lT2EeMuwTp//kyVDUxaaHmBGaN1Ai7DQz44yKAwAnStWFP/lAuxLReQFp4A8wg9e22irkvC3bIMgpKUIheo/58WD03roH5IQsfIsY7oveODIR5s+T1lmIYBBH0IXZqwDOQpArcy82RMMCme6unhJZPIsWqSlVAEWtD89muXdnpvQRFH88exZ1v3WiYYnlJruFoGz7Yi19nrvYI9gkhoee5Idi2m1w1LmDw8EQ==';
const enc = decodeAndEncode(message)

Related

How to convert image file to base64 String in flutter?

I am try to convert a image file in flutter:
File _img=new File('/data/user/0/com.example.test3/app_flutter/2020-10-29T17:18:56.210347.png');
List<int> imageBytes = _img.readAsBytesSync();
String imageB64 = base64Encode(imageBytes);
print(imageB64);
But it look like is a wrong base64 String and I cannot decode to image on convert website:
https://codebeautify.org/base64-to-image-converter
iVBORw0KGgoAAAANSUhEUgAAAhwAAALECAYAAABDk+k+AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAACAASURBVHic7d1ngFx1ucDhd9N77z0hbdMhCSAJVZoURS4C0psColcxFBXFKypKUywUQYp0EdtVQHpHTQLpZZOQnpDee9v7QeUSksxsyP7Ptuf5tnPeybwfCPvLmTNnIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgNJRUFYvXFxcXFxWrw0AVVVBQUGZ/O6vVhYvCgBULYIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhM
Is the dart base64 format is different to another?
Thanks.
You have to convert your bytes into an Uint8List object not a List<int>:
File _img = File(
'/data/user/0/com.example.test3/app_flutter/2020-10-29T17:18:56.210347.png');
final bytes = Uint8List.fromList(_img.readAsBytesSync());
final imgBase64 = base64Encode(bytes);
print(imgBase64);
I find that this case by the 'print' function cannot display fully base64 code.
If want to verify it, need to export to text file:
_write(String text) async {
final File file = File('/storage/emulated/0/xxx/my_file.txt');
await file.writeAsString(text);
print(file);
}

Angular 8 - send file as byte[]

My case is to send a file to the backend but the only file content as byte array eg:
public saveFile(file: File, name: string, description: string): Observable<SymbolResponseEditModel> {
let formData: FormData = new FormData();
formData.append('FileName', name);
formData.append('FileDescription', description);
formData.append('Attachment', file); // <--- this must be a byte array instead of File
return this.http.post<SymbolResponseEditModel>(
'http://senddata.com',
formData
);
Result of this code is that I send to the backend a file containing additional information at the begining
a file containing additional information at the begining as you can see on the picture.
To do this I try to convert the file using file reader but I cannot convert a file to bytearray according to: Getting byte array through input type = file
var reader = new FileReader();
reader.onload = function() {
var arrayBuffer = this.result,
array = new Uint8Array(arrayBuffer),
binaryString = String.fromCharCode.apply(null, array);
console.log(binaryString);
}
reader.readAsArrayBuffer(this.files[0]);
And the error
TS2345: Argument of type 'File' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer | ArrayLike<number>'.
Type 'File' is missing the following properties from type 'SharedArrayBuffer': byteLength, length, [Symbol.species], [Symbol.toStringTag]
The second idea is to remove two lines from the file while downloading because the reasponse content type is octet-stream:
const reader = new FileReader();
reader.addEventListener('loadend', (e) => {
const text = e.srcElement.result; // <-- this text is encoded but I don't want it. Anyway the file is different than I
// sent and i am not able to read it.
let splittedString = text.split('\n');
splittedString = splittedString.splice(2);
let concatenedArray = splittedString.join('\n');
this.fetch(concatenedArray, symbolName);
});
reader.readAsArrayBuffer(response);
This whould work but the reader encode the file.
Have you got any other idea how to send a file as byte array without additional information? Is it possible?

Dart: Converting an int to a Uint8List

I'm trying to length prefix a payload that i'm streaming through a socket, and so far the only way i've been able to get it working is:
Uint8List payload = getPayloadSomehow();
final lBytes = ByteData(4)..setUint32(0, payload.length);
final prefix = lBytes.buffer.asUint8List();
final prefixedPayload = []..addAll(prefix)..addAll(payload);
Creating a ByteData and filling it with the length, and then extracting the buffer as a Uint8List feels very roundabout. But i haven't been able to find a cleaner way to do the conversion and prefixing.
I'd really appreciate it if someone could point me to a better solution, thanks.
How about:
var payload = getPayloadSomehow();
var prefixed = Uint8List(payload.length + 4);
prefixed.buffer.asUint32List(0, 1)[0] = payload.length;
prefixed.setRange(4, prefixed.length, payload);

I want to send \x0a as byte, not as \n

I would like to send a byte string to my device that gets the data from serial port (RS422).
I have to send my byte string as "\x0a\x23\x01..." but Python (2.7) gets \x0a as a new line character (ASCII), therefore I can't send the rest of the bytes.
How can I send "\x0a" as a byte, not as a new line? Below, you can find my code (In the code below, I just write my bytestring to a port, then read&print it on the same device from another port).
import serial
import binascii
class test_Tk():
def __init__(self):
self.serialPortWrite = serial.Serial('COM6', 921600, timeout=0.5)
self.serialPortRead = serial.Serial('COM7', 921600, timeout=0.5)
self.byte1 = "\x0a"
self.byte2 = "\x23"
self.byte3 = "\x01"
self.bytestring = "\xaa\xab\xac\xad"
self.data = self.byte1 + self.byte2 + self.byte3 + self.bytestring
self.serialPortWrite.write(self.data)
self.read = self.serialPortRead.readline(100)
print binascii.hexlify(self.read)
test_Tk()
I get output "0a", however I should have gotten "0a2301aaabacad".
Thanks!

Avoid double slashes from json string json-c

I tried to encode a byte array using glib2.0. After I add the encoded data to a json object, after I send the encoded data through pubnub client,
I got doble slashed string from json.
This is my code :
//code for encoding data
const guchar *data=inputEncodingData;
encodedData=g_base64_encode (data,datalength);
g_print("Encoded data==>%s\n",encodedData);
It produces encoded string with slashes. like this
KA4IChkAGQAAAAAAAAAAAOAO4A4uDgAAAAAAAAoAGAAmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQD//wAAwf/A/8D/AAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAEA//8CAP7/BAD6/wgA9P8SAOb/JwA2/A39mP0AAAIA4P/wD939pf2w/eL87vxz
/Nn7zasAAHMKAADIlAkKGAAYAAAAAAAAAAAA4Jbgls6UAAAAAAAACgAYACYAAAAAAAAAyf+9/7//
vv/B/8D/wP+8/77/v//C/8D/vf+//8D/wP++/77/
This is the code for creating json object:
struct json_object *obj1;
obj1 = json_object_new_object();
json_object_object_add(obj1, "result", json_object_new_string(encodedData));
This will print like this:
KA4IChkAGQAAAAAAAAAAAOAO4A4uDgAAAAAAAAoAGAAmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQD\/\/wAAwf\/A\/8D\/AAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAEA\/\/8CAP7\/BAD6\/wgA9P8SAOb\/JwA2\/A39mP0AAAIA4P\/wD939
pf2w\/eL87vxz\/Nn7zasAAHMKAADIlAkKGAAYAAAAAAAAAAAA4Jbgls6UAAAAAAAACgAYACYAAA
AAAAAAyf+9\/7\/\/vv\/B\/8D\/wP+8\/77\/v\/\/C\/8D\/vf+\/\/8D\/wP++\/77\/
Why is it like this? Any idea? I need data with one slash.

Resources