Skip to content

Instantly share code, notes, and snippets.

@ming900518
Last active July 17, 2023 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ming900518/8470c0d0fda0789e6f45b129fecfeadf to your computer and use it in GitHub Desktop.
Save ming900518/8470c0d0fda0789e6f45b129fecfeadf to your computer and use it in GitHub Desktop.
Node.js 利用 Web Crypto API 產生 RSA 公私鑰範例
const { subtle } = require("node:crypto").webcrypto;
const { writeFileSync } = require("node:fs");
subtle
.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
)
.then(async (key) => {
console.log(key);
writeFileSync("public.pem", await exportPublicKey(key.publicKey));
writeFileSync("private.pem", await exportPrivateKey(key.privateKey));
});
async function exportPrivateKey(key) {
const exported = await subtle.exportKey("pkcs8", key);
const exportedAsString = ab2str(exported);
const exportedAsBase64 = btoa(exportedAsString);
return `-----BEGIN PRIVATE KEY-----\n${exportedAsBase64}\n-----END PRIVATE KEY-----`;
}
async function exportPublicKey(key) {
const exported = await subtle.exportKey("spki", key);
const exportedAsString = ab2str(exported);
const exportedAsBase64 = btoa(exportedAsString);
return `-----BEGIN PUBLIC KEY-----\n${exportedAsBase64}\n-----END PUBLIC KEY-----`;
}
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment