【发布时间】:2011-12-08 09:58:02
【问题描述】:
在 crypto 中,我只看到 Signer/Verifier 用于进行数字签名和使用对称密钥加密的 Cipher/Decipher。
如何使用公钥加密数据?
【问题讨论】:
-
是“Signer”、“Verifier”、“Cipher”和“Decipher”字面量吗?
标签: encryption node.js public-key-encryption
在 crypto 中,我只看到 Signer/Verifier 用于进行数字签名和使用对称密钥加密的 Cipher/Decipher。
如何使用公钥加密数据?
【问题讨论】:
标签: encryption node.js public-key-encryption
正如官方 nodejs api 文档中所述: crypto.publicEncrypt(key, buffer)
用密钥加密缓冲区的内容,并返回一个带有加密内容的新缓冲区。返回的数据可以使用对应的私钥解密,例如使用crypto.privateDecrypt()。
如果 key 不是 KeyObject,则此函数的行为就像 key 已被 传递给 crypto.createPublicKey()。如果是对象,则填充 属性可以传递。否则,此函数使用 RSA_PKCS1_OAEP_PADDING。
因为 RSA 公钥可以从私钥派生,所以一个私钥 可以传递密钥而不是公钥。
所以答案是:
var encrypted = crypto.publicEncrypt(publicKey, buffer);
【讨论】:
您可能对我的NaCl bindings 感兴趣。从它的 API:
// Encrypt and sign
box(message, nonce, pubkey, privkey)
// Decrypt and validate
unbox(box, nonce, pubkey, privkey)
// Generates a new keypair, returns {private: <buffer>, public: <buffer>}
boxKeypair()
// Lengths of nonces and public and private keys in bytes
// { nonce: x, pubkey: x, privkey: x }
lengths.box
另一种方法是使用Cryptographic Message Syntax (CMS)。它不是一个纯粹的 Node.js 解决方案,但您可能拥有所需的所有工具。以下是使用 OpenSSL 的示例:
生成 x509 证书(收件人)和私钥文件(在 Bash 中):
openssl req -nodes -new -x509 -keyout key.pem -out cert.pem
从标准输入加密/解密消息(在 Bash 中):
echo 123 | openssl cms -encrypt -recip cert.pem | openssl cms -decrypt -inkey key.pem
您可以使用 -in/-out 参数来处理文件。下面是一个可用于 Node.js 的示例:
require('child_process').execSync("openssl cms -encrypt -in file.json -recip cert.pem -out file.json.cms")
在 Linux 上,您可能已经安装了 OpenSSL。您可以通过安装Git Bash 在 Windows 上获取 OpenSSL,但您也可以使用内置的 PowerShell 命令。您需要生成PFX 证书(使用New-SelfSignedCertificate)或安装现有证书(也可以使用 OpenSSL 生成)。在证书存储中安装证书后,您可以使用以下命令进行加密/解密:
Protect-CmsMessage -to CN=MyCertName -Path file.json -OutFile file.json.cms
Unprotect-CmsMessage -Path file.json # It will find proper cert in cert store for you
下面是一个示例,如何使用 OpenSSL 从同一私钥生成 .pem 和 PFX 证书,并使 OpenSSL 和 PowerShell 之间的消息可互换。
生成带有扩展名的证书(Windows 需要):
openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout key.pem -out cert.pem -subj '/CN=MyCertName' -addext extendedKeyUsage=1.3.6.1.4.1.311.80.1 -addext keyUsage=keyEncipherment
上述 sn-p 仅适用于较新版本的 OpenSSL (1.1.1)。否则,您需要一个单独的文件来定义扩展名。然后生成一个 PFX 证书(用一些密码保护它):
openssl pkcs12 -export -out certificate.pfx -inkey key.pem -in cert.pem -passout pass:P@ssw0rd
然后将该 PFX 文件复制到您的 Windows 计算机上。您应该能够通过 PowerShell (Import-PfxCertificate) 或手动安装它(单击它并按照向导进行操作,使用所有默认值)。为了使消息可互换,在使用 OpenSSL 时使用 -inform \ -outform 参数。例如:
openssl cms -encrypt -in file.json -recip cert.pem -outform PEM
openssl cms -decrypt -in file.json.cms -inkey key.pem -inform PEM
# If having both OpenSSL/PowerShell on the same OS, use this for testing:
echo test | Protect-CmsMessage -to CN=MyCertName | openssl cms -decrypt -inform PEM -inkey key.pem
顺便说一句,CmsMessage 命令将在 PowerShell Core 7.1 上可用,因此您也可以在 Linux/Mac 上使用它(现在处于预览状态,稳定版本将于 2020 年 12 月发布)。
【讨论】: