jojo
jojo

Reputation: 13863

How to convert ArrayBuffer from SubtleCrypto.sign to a string

I am working on a project that needs to deal with crypto on the client side. We generate a private/public key pair. In the client side we use the crypto key to create a signature for every payload we send to server.

https://en.wikipedia.org/wiki/UTF-8#Description
const arrayBufferInUniCode = stringToArrayBufferInUnitCode("foo");

const signatureArrayBuffer = await SubtleCrypto.sign({name: "HMAC",hash: { name: "SHA-256"}}, {private key}, arrayBufferInUniCode);

But seems like the array buffer returned from sign is not in unicode format. If I try to process it as defined in https://en.wikipedia.org/wiki/UTF-8#Description to try to turn it into a string, it doesn't work -- it doesn't contains the right bytes sequence.

Any idea how to process the array buffer from the sign function

Upvotes: 1

Views: 1084

Answers (1)

zaph
zaph

Reputation: 112855

Encryption is binary and arbitrary binary is not valid unicode. Thus the encrypted output is not generally unicode.

Just save as binary or if a character encoding is needed convert the encrypted data to ASCII using Base64 encoding. On decryption convert back to binary prior to decryption.

Upvotes: 1

Related Questions