In order to store buffer values returned from the API as string I’m searching for a way to properly convert utf8array buffers to String and vice versa. I’ve tried many ways but for some Arrays I always get different values when converting back from string to buffer.
Here’s my code to see / reproduce my problem:
I’ve two functions for conversion:
function stringToArray(bufferString) {
let uint8Array = new TextEncoder("utf-8").encode(bufferString);
return uint8Array;
}
function arrayToString(bufferValue) {
return new TextDecoder("utf-8").decode(bufferValue);
}
Here is my test code:
let encKeyPairHandle = await window.safeCrypto.generateEncKeyPair(appHandle);
let pubEncKeyHandle = await window.safeCryptoKeyPair.getPubEncKey(encKeyPairHandle);
let rawPubEncKey = await window.safeCryptoPubEncKey.getRaw(pubEncKeyHandle);
console.log(rawPubEncKey.buffer);
let rawPubEncKeyStr = arrayToString(rawPubEncKey.buffer);
rawPubEncKey = stringToArray(rawPubEncKeyStr);
console.log(rawPubEncKey);
As you can see, I convert the buffer into a string and then back again. However the two values are not the same. The second one is longer and different from the first one. Here is my console output:
Uint8Array(32) [228, 60, 188, 226, 76, 55, 247, 204, 126, 72, 202, 159, 6, 112, 162, 47, 188, 255, 124, 94, 25, 172, 141, 111, 0, 239, 119, 67, 128, 155, 116, 52]
Uint8Array(58) [239, 191, 189, 60, 239, 191, 189, 239, 191, 189, 76, 55, 239, 191, 189, 239, 191, 189, 126, 72, 202, 159, 6, 112, 239, 191, 189, 47, 239, 191, 189, 239, 191, 189, 124, 94, 25, 239, 191, 189, 239, 191, 189, 111, 0, 239, 191, 189, 119, 67, 239, 191, 189, 239, 191, 189, 116, 52]
I’ve searched and found that many people seem to struggle converting such arrays in javascript. For instance I’ve also tried this implementation here: https://gist.github.com/joni/3760795 but it also doesn’t produce equal arrays. Interestingly, if I try my functions on a simple string (like “Hello”) it works without problems. It seems to be a problem with the utf-8 chars.
Has anyone found a solution for this which works for all kind of strings / buffers?