节点js加密符号返回空字符串

时间:2022-05-09 18:24:13

I am wanting to sign a string with a private key using crypto.

我想使用crypto使用私钥签名字符串。

The sign method returns an empty string, I was hoping to get a signiture.

sign方法返回一个空字符串,我希望得到一个签名。

var crypto = require('crypto');
var message = "This is a string I want to ensure is not tampered with.";

var diffieHellman = crypto.createDiffieHellman(1024);
var publicKey = diffieHellman.generateKeys("base64");
var privateKey = diffieHellman.getPrivateKey("base64");

var signer = crypto.createSign('RSA-SHA256');
signer.write(message, "ascii", function()
{
    var signature = signer.sign(privateKey, 'base64');

    console.log(publicKey);
    console.log(privateKey);
    console.log(signature);// Empty string ?
});

The public key and private key are generated fine.

公钥和私钥生成正常。

Any help would be much appreciated.

任何帮助将非常感激。

2 个解决方案

#1


1  

The key needed for sign(...) is a PEM encoded RSA key but the key generated by createDiffieHellman is not that as far as I know. I think your best bet would be to generate a PEM key with OpenSSL.

sign(...)所需的密钥是PEM编码的RSA密钥,但createDiffieHellman生成的密钥并不是我所知道的。我认为你最好的选择是用OpenSSL生成一个PEM密钥。

#2


0  

This is a bug with crypto, confirmed here :

这是加密的错误,在此确认:

https://github.com/joyent/node/issues/6963

To solve, use a bit length of 512 and signer.

要解决,请使用512位签名和签名者。

Here is working code

这是工作代码

var keypair = require('keypair');
var crypto = require('crypto');

var dataA = "This is a string I do not want to be tampered with";
var dataB = "This is a string I do want to be tampered with";

var pair = keypair({bits:256});
console.log("Private   :"+pair['private']);
console.log(" Public   :"+pair['public']);

var sign = crypto.createSign('RSA-SHA256');
sign.write(dataA);
var signiture = sign.sign(pair['private'],'base64');

console.log("Signiture :"+signiture);

#1


1  

The key needed for sign(...) is a PEM encoded RSA key but the key generated by createDiffieHellman is not that as far as I know. I think your best bet would be to generate a PEM key with OpenSSL.

sign(...)所需的密钥是PEM编码的RSA密钥,但createDiffieHellman生成的密钥并不是我所知道的。我认为你最好的选择是用OpenSSL生成一个PEM密钥。

#2


0  

This is a bug with crypto, confirmed here :

这是加密的错误,在此确认:

https://github.com/joyent/node/issues/6963

To solve, use a bit length of 512 and signer.

要解决,请使用512位签名和签名者。

Here is working code

这是工作代码

var keypair = require('keypair');
var crypto = require('crypto');

var dataA = "This is a string I do not want to be tampered with";
var dataB = "This is a string I do want to be tampered with";

var pair = keypair({bits:256});
console.log("Private   :"+pair['private']);
console.log(" Public   :"+pair['public']);

var sign = crypto.createSign('RSA-SHA256');
sign.write(dataA);
var signiture = sign.sign(pair['private'],'base64');

console.log("Signiture :"+signiture);