本文介绍了将 webcrypto 密钥导出为 PEM 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WebCrypto 和 RSASSA-PKCS1-v1_5 (https://github.com/diafygi/webcrypto-examples#rsassa-pkcs1-v1_5---sign),我需要使用javascript代码将公钥导出为PEM格式.

I am using WebCrypto with RSASSA-PKCS1-v1_5 (https://github.com/diafygi/webcrypto-examples#rsassa-pkcs1-v1_5---sign) and I need to export the public key to PEM format using javascript code.

文档说可以通过这种方式导出密钥:https://github.com/diafygi/webcrypto-examples#rsassa-pkcs1-v1_5---exportkey但我需要不同的格式.

The documentation says that is possible to export the key in this way:https://github.com/diafygi/webcrypto-examples#rsassa-pkcs1-v1_5---exportkeybut I need a different format.

有什么想法吗?

提前致谢.

问候

推荐答案

将公钥导出到 spki

window.crypto.subtle.exportKey("spki",keys.publicKey);

并将结果数组缓冲区转换为 base64 添加 PEM 标头 -----BEGIN PUBLIC KEY----------END PUBLIC KEY-----.下面我提供了函数 spkiToPEM 和一个完整的例子

And convert the resulting array buffer to base64 adding the PEM headers -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY-----. Below I provide the function spkiToPEM with a full example

crypto.subtle.generateKey(
    {
        name: "RSASSA-PKCS1-v1_5",
        modulusLength: 2048,
        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
        hash: {name: "SHA-256"},
    },
    false,
    ["sign", "verify"]
).then(function(keys){
    return window.crypto.subtle.exportKey("spki",keys.publicKey);
}).then (function(keydata){
    var pem = spkiToPEM(keydata);
    console.log(pem);
}).catch(function(err){
    console.error(err);
});

function spkiToPEM(keydata){
    var keydataS = arrayBufferToString(keydata);
    var keydataB64 = window.btoa(keydataS);
    var keydataB64Pem = formatAsPem(keydataB64);
    return keydataB64Pem;
}

function arrayBufferToString( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return binary;
}


function formatAsPem(str) {
    var finalString = '-----BEGIN PUBLIC KEY-----\n';

    while(str.length > 0) {
        finalString += str.substring(0, 64) + '\n';
        str = str.substring(64);
    }

    finalString = finalString + "-----END PUBLIC KEY-----";

    return finalString;
}

这篇关于将 webcrypto 密钥导出为 PEM 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 02:14