Skip to content

Commit

Permalink
Add usage examples of the k6/experimental/webcrypto module
Browse files Browse the repository at this point in the history
  • Loading branch information
oleiade committed Apr 6, 2023
1 parent 08836fd commit 316550b
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions examples/experimental/webcrypto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { crypto } from "k6/experimental/webcrypto";

export default async function () {
const key = await crypto.subtle.generateKey(
{
name: "AES-CBC",
length: 256,
},
true,
["encrypt", "decrypt"]
);

const encoded = stringToArrayBuffer("Hello, World!");
const iv = crypto.getRandomValues(new Uint8Array(16));

const ciphertext = await crypto.subtle.encrypt(
{
name: "AES-CBC",
iv: iv,
},
key,
encoded
);

const plaintext = await crypto.subtle.decrypt(
{
name: "AES-CBC",
iv: iv,
},
key,
ciphertext,
);

console.log("deciphered text == original text: ", arrayBufferToHex(plaintext) === arrayBufferToHex(encoded))
}

function arrayBufferToHex(buffer) {
return [...new Uint8Array(buffer)]
.map((x) => x.toString(16).padStart(2, "0"))
.join("");
}

function stringToArrayBuffer(str) {
var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}

0 comments on commit 316550b

Please sign in to comment.