将Web加密密钥导出为RSA XML格式

时间:2019-06-27 12:55:55

标签: javascript cryptography rsa

我正在尝试将crypto.subtle生成的密钥导出为RSAXML格式

我有以下示例,该示例在大多数情况下都有效,但是当我通过以下XML到PEM转换器运行它时,有时会导致BadData。有人可以在这里看到我在做什么错吗?

https://superdry.apphb.com/tools/online-rsa-key-converter

使用c#命令rsa.FromXmlString(rsaString);

,这些生成的密钥也会失败

这里是一个jsfiddle,显示了正在生成到控制台的密钥

https://jsfiddle.net/f78kpLqr/1/

const example = async() => {
    const rsaKey = await crypto.subtle.generateKey({
        name: 'RSA-OAEP',
        modulusLength: 2048,
        publicExponent: new Uint8Array([1, 0, 1]),
        hash: {
            name: 'SHA-1'
        }
    }, true, // can extract it later if we want
    ['encrypt', 'decrypt']);

    const privateKey = await crypto.subtle.exportKey('jwk', rsaKey.privateKey);

    const convB64 = function (str) {
        str = str.replace(/\-/g, '+').replace(/\_/g, '/');
        while (str.length % 4 != 0) str += '=';
        return str;
    };
    let st = '<RSAKeyValue>';
    st += '<Exponent>AQAB</Exponent>';
    st += `<Modulus>${convB64(privateKey.n)}</Modulus>`;

    if (privateKey.d) {
        st += `<D>${convB64(privateKey.d)}</D>`;
        st += `<P>${convB64(privateKey.p)}</P>`;
        st += `<Q>${convB64(privateKey.q)}</Q>`;
        st += `<DP>${convB64(privateKey.dp)}</DP>`;
        st += `<DQ>${convB64(privateKey.dq)}</DQ>`;
        st += `<InverseQ>${convB64(privateKey.qi)}</InverseQ>`;
    }

    st += '</RSAKeyValue>';
   console.log(st);
}

example();

由此生成的示例密钥如下,该密钥使在线转换器失败,并带有“ BAD DATA”响应。

<RSAKeyValue><Exponent>AQAB</Exponent><Modulus>0E/le1HcVhJh6pNAh5LM0dm360YmEU03ELTvGtGu0yteUwsaq9frV8D6D2gzxgQdxcqw39KRo0aBoxIxaQZlKwLBenD8v86jNxf9ketc/k0xpzaPaPDSYCuIYe3PTHhYG5+K6AkVIXuFHsOU1Ci4pOxRFNTIM9RNeCZ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