在 Node.js 加密中使用 sign.sign() 时出错,解密错误

Error using sign.sign() in Node.js crypto, bad decrypt

node.js 的新手,我在 crypto.Please 帮助中使用 sign() 时出错!

我创建了标志 使用 const sign = crypto.createSign('sha256'); 然后尝试使用 var signature = sign.sign(key,'hex'); 签名密钥是使用

生成的
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret'
  }
});

const key = privateKey;
const seller_public_key = publicKey

我尝试签名的是一个 JSON 对象,该对象使用 jsonData = JSON.stringify(menu);return signData(jsonData);

转换为字符串
function signData(plaintext){
  sign.update(plaintext);
  sign.end();
  var signature = sign.sign(key,'hex');
  return signature;
}

我收到错误消息:

internal/crypto/sig.js:80
  var ret = this._handle.sign(key, passphrase, rsaPadding, pssSaltLength);
                         ^

Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

而且我看到有人说密钥格式,我的密钥格式确实以-----BEGIN ENCRYPTED PRIVATE KEY-----开头,以-----END ENCRYPTED PRIVATE KEY-----

结尾

由于您的私钥已加密,您应该在 sign 调用中传递密码:

sign.sign({ key, passphrase: 'top secret' }, 'hex');

The privateKey argument can be an object or a string. If privateKey is a string, it is treated as a raw key with no passphrase. If privateKey is an object, it must contain one or more of the following properties:

  • key: - PEM encoded private key (required)

  • passphrase: - passphrase for the private key

  • ...

参考:https://nodejs.org/docs/latest-v10.x/api/crypto.html#crypto_sign_sign_privatekey_outputencoding