使用公钥在node.js中encryption数据

我需要使用公钥(pem文件)encryption一个string,然后使用私钥(也是一个pem)对其进行签名。

我正在加载pem文件罚款:

publicCert = fs.readFileSync(publicCertFile).toString(); 

但经过几个小时的淘谷歌,我似乎无法find一种方法来使用公钥encryption数据。 在PHP中,我只是简单地调用openssl_public_encrypt,但在节点或任何模块中看不到任何相应的function。

如果有人有任何build议,让我知道。

没有图书馆必要的朋友

input密码

下面是一个可用于使用RSA密钥encryption/解密string的小巧模块:

 var crypto = require("crypto"); var path = require("path"); var fs = require("fs"); var encryptStringWithRsaPublicKey = function(toEncrypt, relativeOrAbsolutePathToPublicKey) { var absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey); var publicKey = fs.readFileSync(absolutePath, "utf8"); var buffer = new Buffer(toEncrypt); var encrypted = crypto.publicEncrypt(publicKey, buffer); return encrypted.toString("base64"); }; var decryptStringWithRsaPrivateKey = function(toDecrypt, relativeOrAbsolutePathtoPrivateKey) { var absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey); var privateKey = fs.readFileSync(absolutePath, "utf8"); var buffer = new Buffer(toDecrypt, "base64"); var decrypted = crypto.privateDecrypt(privateKey, buffer); return decrypted.toString("utf8"); }; module.exports = { encryptStringWithRsaPublicKey: encryptStringWithRsaPublicKey, decryptStringWithRsaPrivateKey: decryptStringWithRsaPrivateKey } 

我build议在可能的情况下不要使用同步fs方法,并且可以使用Promise使其更好,但对于简单用例,这是我已经看到的工作方法

更新的公共/私人解密和encryption模块是URSA。 node-rsa模块已过时。

这个Node模块为OpenSSL的RSA公钥/私钥encryptionfunction提供了一套相当完整的包装。

npm安装ursa

请参阅: https : //github.com/Obvious/ursa

那么这个node-rsa模块呢? 这里是test.js文件的一个链接,演示了用法 。

TL; DR:Ursa是你最好的select。 它真的很时髦,这不符合标准的节点encryption。

我发现的任何其他解决scheme都不能在Windows中工作,或者实际上不是encryption库。 路易推荐的大熊看起来是最好的select。 如果你不关心窗户,你更加黄金。 关于Ursa,我必须安装Open SSL以及一些名为“Visual C ++ 2008 Redistributables”的东西,才能让npm install正常工作。 在这里获取垃圾: http : //slproweb.com/products/Win32OpenSSL.html

细目:

这实际上是我所能find的。

这不是由节点版本v0.11.13或更低版本本身支持的,但似乎下一个版本的节点(又名v0.12)将支持这一点。

这里是线索: https : //github.com/joyent/node/blob/v0.12/lib/crypto.js#L358

请参阅crypto.publicEncryptcrypto.privateDecrypt

以下是这个https://github.com/joyent/node/blob/7c0419730b237dbfa0ec4e6fb33a99ff01825a8f/doc/api/crypto.markdown#cryptopublicencryptpublic_key-buffer的未来文档