🏮

浏览器生成 RSA 证书

date
Mar 3, 2021
slug
Browser-generating-RSA-certificate
status
Published
tags
前端
JavaScript
summary
type
Post
Property
Mar 2, 2022 04:45 PM
将内容复制粘贴到你的浏览器控制台里(推荐 Chrome ),然后执行即可。
会自动下载到两个名为 “rsa.pub” 和 “rsa.key” 文件。
(async () => { const ab2str = (buffer) => String.fromCharCode.apply(null, new Uint8Array(buffer)); const saveFile = async (files) => { Object.keys(files).forEach(file => { const blob = new Blob([files[file]], { type: 'text/plain' }); with (document.createElement('a')) { download = file; href = URL.createObjectURL(blob); click(); } URL.revokeObjectURL(blob); }); } const exportKey = (content) => new Promise(async (resolve) => { await crypto.subtle.exportKey(content.type === "private" ? "pkcs8" : "spki", content).then((data) => resolve(`-----BEGIN ${content.type.toUpperCase()} KEY-----\n${btoa(ab2str(data))}\n-----END ${content.type.toUpperCase()} KEY-----`)); }); const { privateKey, publicKey } = await crypto.subtle.generateKey({ name: "RSA-OAEP", modulusLength: 4096, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["encrypt", "decrypt"]) saveFile({ "rsa.key": await exportKey(privateKey), "rsa.pub": await exportKey(publicKey) }); })();