Skip to content

Commit

Permalink
Add example which generates, exports and imports key in pkcs8 format
Browse files Browse the repository at this point in the history
  • Loading branch information
timonson committed Sep 15, 2021
1 parent 316ae90 commit b154f20
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/example_deps.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { serve } from "https://deno.land/[email protected]/http/server.ts";
export * as base64 from "https://deno.land/[email protected]/encoding/base64.ts";
55 changes: 55 additions & 0 deletions examples/pkcs8_storing_example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { base64 } from "./example_deps.ts";

/*
Import a PEM encoded RSA private key, to use for RSA-PSS signing.
Takes a string containing the PEM encoded key, and returns a Promise
that will resolve to a CryptoKey representing the private key.
*/
function importPrivateKey(pem: string) {
// fetch the part of the PEM string between header and footer
const pemHeader = "-----BEGIN PRIVATE KEY-----";
const pemFooter = "-----END PRIVATE KEY-----";
const pemContents = pem.substring(
pemHeader.length,
pem.length - pemFooter.length,
);
const binaryDer = base64.decode(pemContents).buffer;
return window.crypto.subtle.importKey(
"pkcs8",
binaryDer,
{
name: "RSASSA-PKCS1-v1_5",
hash: "SHA-384",
},
true,
["sign"],
);
}

async function generatePemFromPrivateCryptoKey(privateKey: CryptoKey) {
const exportedKey = await crypto.subtle.exportKey("pkcs8", privateKey);
const exportedAsBase64 = base64.encode(exportedKey);
return `-----BEGIN PRIVATE KEY-----\n${exportedAsBase64}\n-----END PRIVATE KEY-----`;
}

const keyRS384CryptoKeyPair = await window.crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-384",
},
true,
["verify", "sign"],
);

const { privateKey, publicKey } = keyRS384CryptoKeyPair;

const pemExported = await generatePemFromPrivateCryptoKey(privateKey);

const importedCryptoKey = await importPrivateKey(pemExported);

const areEqualKeys =
pemExported === await generatePemFromPrivateCryptoKey(importedCryptoKey);

console.log(areEqualKeys);

0 comments on commit b154f20

Please sign in to comment.