0
Generate an RSA PSS key pair
One script reply has been approved by the moderators Verified

Generate a license key pair using RSA PSS for creating signature, useful for generating license keys for instance

Created by admin 466 days ago Viewed 4748 times
0
Submitted by admin Deno
Verified 466 days ago
1
export async function main() {
2
  const keys = await window.crypto.subtle.generateKey(
3
    {
4
      name: "RSA-PSS",
5
      modulusLength: 1024,
6
      publicExponent: new Uint8Array([1, 0, 1]),
7
      hash: "SHA-256",
8
    },
9
    true,
10
    ["sign", "verify"],
11
  );
12
  return {
13
    private: await exportKey(keys.privateKey, true),
14
    public: await exportKey(keys.publicKey, false),
15
  };
16
}
17

18
async function exportKey(key: CryptoKey, isPrivateKey: boolean) {
19
  const exported = await window.crypto.subtle.exportKey(
20
    isPrivateKey ? "pkcs8" : "spki",
21
    key,
22
  );
23
  const exportedAsString = ab2str(exported);
24
  const exportedAsBase64 = window.btoa(exportedAsString);
25
  const pemExported = `-----BEGIN ${
26
    isPrivateKey ? "PRIVATE" : "PUBLIC"
27
  } KEY-----\n${exportedAsBase64}\n-----END PRIVATE KEY-----`;
28

29
  return pemExported;
30
}
31

32
function ab2str(buf: ArrayBuffer) {
33
  return String.fromCharCode.apply(null, new Uint8Array(buf));
34
}
35