简体   繁体   English

如何生成在 node.js 和浏览器中都有效的 RSA 对

[英]How can I generate an RSA pair that works both in node.js and browser

I want to achieve RSA encryption between a node server and a browser.我想在节点服务器和浏览器之间实现 RSA 加密。 So far I've used node-rsa on the server:到目前为止,我在服务器上使用了 node-rsa:

const RSA = require("node-rsa")
const key = new RSA({b: 512});
console.log(key.exportKey("public"))

And it looks like this:它看起来像这样:

-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMSZQk6XJbPTr/0bY1OYQUPkUXfsC4K8
iPywjTpIDLZhw341cxPaiI0dxkP/GLvG+03xqboFMRFJbs4L5aXA9x0CAwEAAQ==
-----END PUBLIC KEY-----

How can I do the same thing in browser.我怎样才能在浏览器中做同样的事情。
PS I've tried SubtleCrypto API put I can't figure out how to produce a similar format as in node-rsa. PS 我已经尝试过 SubtleCrypto API ,但我不知道如何生成与 node-rsa 中类似的格式。

What you see is a PEM encoded SubjectPublicKeyInfo or "spki" for short.您看到的是 PEM 编码的 SubjectPublicKeyInfo 或简称“spki”。 Helpfully, the official SuptleCrypto API offers an example code snippet that shows how to create the binary structure and put it in PEM format.有用的是, 官方的 SuptleCrypto API提供了一个示例代码片段,展示了如何创建二进制结构并将其放入 PEM 格式。

The node-rsa NodeJS library incorrectly calls this 'pkcs8' or more specifically 'pkcs8-public' (at least, that's what I can grok from their documentation). node-rsa NodeJS 库错误地将其称为'pkcs8'或更具体地称为'pkcs8-public' (至少,这是我可以从他们的文档中了解到的)。 I've created bug report 208 which you can vote on.我创建了您可以投票的错误报告 208

I've found this code for the client side that can generate an RSA pair and export the public key (for some reason it doesn't work for the private one).我为客户端找到了这段代码,它可以生成一个 RSA 对并导出公钥(由于某种原因,它不适用于私钥)。

async function exportCryptoKey(key) {
    const exportedAsBase64 = window.btoa(String.fromCharCode.apply(null, new Uint8Array(await window.crypto.subtle.exportKey("spki", key))))
    return `-----BEGIN PUBLIC KEY-----\n${exportedAsBase64}\n-----END PUBLIC KEY-----`
}
async function main(){
    keyPair = await window.crypto.subtle.generateKey({
            name: "RSA-OAEP",
            modulusLength: 2048,
            publicExponent: new Uint8Array([1, 0, 1]),
            hash: "SHA-256",
        }, true, ["encrypt", "decrypt"])
    console.log(await exportCryptoKey(keyPair.publicKey))
}
main()

You need to install browserify for using nodejs require() method in browser.您需要安装 browserify 才能在浏览器中使用 nodejs require() 方法。

run this in your terminal:在您的终端中运行它:

npm install browserify

then,然后,

browserify index.js //"your current js file_name// -o bundle.js

now use this bundle.js in your html现在在你的 html 中使用这个 bundle.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM