Reputation: 195
Hi so am trying to convert this C# function to NodeJS but it does not work I don't really know what is wrong lemme show some code and outputs
C#:
private static byte[] ConvertMsg(byte[] message, byte type = 255, byte cmd = 255)
{
int msgLength = message.Length;
byte[] bArray = new byte[msgLength + 3];
bArray[0] = type;
bArray[1] = cmd;
Buffer.BlockCopy(message, 0, bArray, 2, msgLength);
bArray[msgLength + 2] = 0;
return bArray;
}
static void Main()
{
byte[] encrypted = ConvertMsg(Encoding.Default.GetBytes("hi"),3,3);
Console.WriteLine($"Encrypted: {Convert.ToBase64String(encrypted)}");
Console.ReadKey();
}
Output:
AwNoaQA=
NodeJS:
function ConvertMsg(message, type=255, cmd=255){
let length = message.length;
let bArray = Buffer.alloc(length+3);
bArray[0] = type;
bArray[1] = cmd;
bArray.copy(message,0,length);
bArray[length + 2] = 0;
return bArray;
}
let encrypted = ConvertMsg(Buffer.from("hi"),3,3);
console.log(encrypted.toString("base64"));
Output:
AwMAAAA=
As you can see the output is not the same any help is much appreciated, please explain when you answer I would like to learn more thank you.
Upvotes: 2
Views: 7045
Reputation: 34189
According to Buffer
documentation, .copy(target[, targetStart[, sourceStart[, sourceEnd]]])
Copies data from a region of buf to a region in target even if the target memory region overlaps with buf.
Here
// means copy 'bArray' starting from length to 'message' starting from 0
bArray.copy(message, 0, length);
You do not copy contents of message
to bArray
. You do the opposite thing - you copy bArray
contents, which is [3, 3, 0, 0, 0]
by now to message
, and actually overwrite your message.
Then, you output this bArray
, which results in AwMAAAA=
which is Base64 representation of [3, 3, 0, 0, 0]
.
You may want to change your function in this way:
function ConvertMsg(message, type=255, cmd=255){
let length = message.length;
let bArray = Buffer.alloc(length + 3);
bArray[0] = type;
bArray[1] = cmd;
// means copy 'message' starting from 0 to 'bArray' starting from 2
message.copy(bArray, 2);
bArray[length + 2] = 0;
return bArray;
}
Upvotes: 4