如果有人正在寻找更现代的解决方案,这里是@pedrofb 的解决方案es-next
:
const getPublicKey = async () => {
const options = {
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-256' },
};
const keys = await window.crypto.subtle.generateKey(
options,
false, // non-exportable (public key still exportable)
['sign', 'verify'],
);
const publicKey = await window.crypto.subtle.exportKey('spki', keys.publicKey);
let body = window.btoa(String.fromCharCode(...new Uint8Array(publicKey)));
body = body.match(/.{1,64}/g).join('\n');
return `-----BEGIN PUBLIC KEY-----\n${body}\n-----END PUBLIC KEY-----`;
};
利用:
getPublicKey().then(value => console.log(value));
输出:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2NYY4J3mY6DjmhwxRRK9
UMdTx7RnoteFAAlaqkV3jff3o+O8h/NtAi1jnsrMp6SOewdO9Ae8htV5CK7WZ3yX
cJ5hR5yGCcgKcDYSP1PKb9aqp4vGOjrbAhTcJyIs/qjBqtxcYY/oICKMV3Lmmf/E
WJKtXaKJBk5v97XuBuX1ccaNaU7WxW5QayR0kR0oyJh21WJjHaVQEoLABIao+8fy
d/p2nu/BLvPrtIy76M+VrfK0V45ODC0dolx0XtWRhI9odrBBayOvuIwa4nrLYI0W
Y2QW5aQM5R7JddA6KxiVsQr3JsWncEdw/wOkMtKXMEQcmqLldDQgGCOVNxy4saRl
VwIDAQAB
-----END PUBLIC KEY-----