Last active
July 17, 2023 06:26
-
-
Save ming900518/8470c0d0fda0789e6f45b129fecfeadf to your computer and use it in GitHub Desktop.
Node.js 利用 Web Crypto API 產生 RSA 公私鑰範例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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