Skip to content

Commit

Permalink
docs: unifying of derive bits examples
Browse files Browse the repository at this point in the history
  • Loading branch information
olegbespalov committed Apr 18, 2024
1 parent 1f95db2 commit 4298568
Showing 1 changed file with 78 additions and 40 deletions.
118 changes: 78 additions & 40 deletions examples/derive_bits/derive-bits-ecdh.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,93 @@
import { crypto } from "k6/x/webcrypto";

export default async function () {
try {
// Generate a key pair for Alice
const aliceKeyPair = await crypto.subtle.generateKey(
// Generate a key pair for Alice
crypto.subtle
.generateKey(
{
name: "ECDH",
namedCurve: "P-256",
},
true,
["deriveKey", "deriveBits"]
);
)
.then(
(aliceKeyPair) => {
// generate a key pair for Bob
crypto.subtle
.generateKey(
{
name: "ECDH",
namedCurve: "P-256",
},
true,
["deriveKey", "deriveBits"]
)
.then(
(bobKeyPair) => {
// Derive shared secret for Alice
crypto.subtle
.deriveBits(
{
name: "ECDH",
public: bobKeyPair.publicKey,
},
aliceKeyPair.privateKey,
256
)
.then(
(aliceSharedSecret) => {
console.log(
"operation successful, alice shared secret: " +
printArrayBuffer(aliceSharedSecret)
);
},
(err) => {
console.error(
"Alice Shared Secret generation, got unexpected error: " +
err
);
}
);

// Generate a key pair for Bob
const bobKeyPair = await crypto.subtle.generateKey(
{
name: "ECDH",
namedCurve: "P-256",
// Derive shared secret for Bob
crypto.subtle
.deriveBits(
{
name: "ECDH",
public: aliceKeyPair.publicKey,
},
bobKeyPair.privateKey,
256
)
.then(
(bobSharedSecret) => {
console.log(
"operation successful, bob shared secret: " +
printArrayBuffer(bobSharedSecret)
);
},
(err) => {
console.error(
"Bob Shared Secret generation, got unexpected error: " +
err
);
}
);
},
(err) => {
console.error(
"Bob Key Pair generation, got unexpected error: " + err
);
}
);
},
true,
["deriveKey", "deriveBits"]
(err) => {
console.error(
"Alice Key Pair generation, got unexpected error: " + err
);
}
);

// Derive shared secret for Alice
const aliceSharedSecret = await deriveSharedSecret(
aliceKeyPair.privateKey,
bobKeyPair.publicKey
);

// Derive shared secret for Bob
const bobSharedSecret = await deriveSharedSecret(
bobKeyPair.privateKey,
aliceKeyPair.publicKey
);

console.log("alice shared secret: " + printArrayBuffer(aliceSharedSecret));
console.log("bob shared secret: " + printArrayBuffer(bobSharedSecret));
} catch (err) {
console.log("Error: " + JSON.stringify(err));
}
}

async function deriveSharedSecret(privateKey, publicKey) {
return crypto.subtle.deriveBits(
{
name: "ECDH",
public: publicKey, // An ECDH public key from the other party
},
privateKey, // Your ECDH private key
256 // the number of bits to derive
);
}

const printArrayBuffer = (buffer) => {
Expand Down

0 comments on commit 4298568

Please sign in to comment.