我想从jwk
端点下载公钥,并将其转换为jwt
的sing
函数所需的pem
。
export type Secret =
| string
| Buffer
| { key: string | Buffer; passphrase: string };
jwk
可以使用subtle
从crypto
导入为JsonWebKey
类型的webKey
,并返回为CryptoKey
const pubKey = await subtle.importKey(
"jwk",
webKey,
{ hash: 'SHA-256', name: 'RSA-OAEP' },
true,
[]
);
CryptoKey
可与subtle.exportKey
一起导出,但结果在ByteArray
中,并将其转换为pem
(1.将字节转换为字符,然后2.转换为base64),然后将其添加到-----BEGIN PUBLIC KEY-----
(带信封,每64个字符添加一行),生成无效密钥。
/**
* Exports the given key into the specified format, if supported.
*
* If the `<CryptoKey>` is not extractable, the returned promise will reject.
*
* When `format` is either `'pkcs8'` or `'spki'` and the export is successful,
* the returned promise will be resolved with an `<ArrayBuffer>` containing the exported key data.
*
* When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a
* JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification.
* @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
* @returns `<Promise>` containing `<ArrayBuffer>`.
* @since v15.0.0
*/
exportKey(format: 'jwk', key: CryptoKey): Promise<JsonWebKey>;
exportKey(format: Exclude<KeyFormat, 'jwk'>, key: CryptoKey): Promise<ArrayBuffer>;
此外,发布密钥只能导出到spki
和jwk
,而raw
不受支持。
问题是如何尽可能简单地将jwk
转换为pem
?!
1条答案
按热度按时间jjhzyzn01#
技巧是用
static from(key: webcrypto.CryptoKey): KeyObject;
将CryptoKey
转换为KeyObject
,然后使用KeyObject
的成员export(options: KeyExportOptions<'pem'>): string | Buffer;
。函数将为
托帕科的建议
使用
createPublicKey
会更容易,因为createPublicKey
接受JsonWebKeyInput
并生成可以轻松导出的KeyObject
。那么