I got a code to encrypt some text in PHP, it looks like this:
$key = '1234aaaff80b56233525ac2355ac3456'; // something like this
$utf16Content = mb_convert_encoding('Some text', 'UTF-16LE');
$cipher = 'aes-256-gcm';
$nonceLength = openssl_cipher_iv_length($cipher);
$nonce = openssl_random_pseudo_bytes($nonceLength);
$encryptedContent = openssl_encrypt($utf16Content, $cipher, $key, $options=0, $nonce, $tag);
How could I implement the same behavior in JS webcrypto? (I need that for the k6 tests) I found a documentation but it isn’t clear for me.
For now I have code like this but I cannot decrypt that successfully so I guess something isn’t right.
const rawKey = Uint8Array.from(new String('1234aaaff80b56233525ac2355ac3456'), (x) => x.charCodeAt(0));
const key = await crypto.subtle.importKey(
'raw',
rawKey,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
const nonce = crypto.getRandomValues(new Uint8Array(12));
const authTag = crypto.getRandomValues(new Uint8Array(10));
const encrypted = await crypto.subtle.encrypt({
name: 'AES-GCM',
iv: nonce,
additionalData: authTag,
},
key,
stringToArrayBuffer('Some text')
);
function stringToArrayBuffer(str) {
const buf = new ArrayBuffer(str.length * 2);
const bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
I think the main problem is creating correct authTag
and changing String rawKey to ArrayBuffer.