使用node.js加密来验证签名

时间:2018-02-04 17:35:07

标签: node.js digital-signature public-key-encryption

我正在尝试使用AWS lambda验证在swift中使用sec256r1创建的签名。

消息:“要签署的一些文字”

已经用sha256进行了哈希

签名将在base64

encoding:MEYCIQCPfWhpzxMqu3gZWflBm5V0aetgb2/S+SGyGcElaOjgdgIhALaD4lbxVwa8HUUBFOLz+CGvIioDkf9oihSnXHCqh8yV

和公钥看起来像这样:

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEXIvPbzLjaPLd8jgiv1TL/X8PXpJN
gDkGRj9U9Lcx1yKURpQFVavcMkfWyO8r7JlZNMax0JKfLZUM1IePRjHlFw==
-----END PUBLIC KEY-----

澄清,

我正在尝试使用lambda来验证来自客户端的签名,并在需要时使用其公钥加密数据。

这是代码:

    const crypto = require('crypto');
    const verify = crypto.createVerify('SHA256');

    verify.write('some text to sign');
    verify.end();

    const l1 = "-----BEGIN PUBLIC KEY-----\n"
    const l2 = 
  "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEXIvPbzLjaPLd8jgiv1TL/X8PXpJNgDkGRj9U9Lcx1yKURpQFVavcMkfWyO8r7JlZNMax0JKfLZUM1IePRjHlFw=="

    const l3 = "\n-----END PUBLIC KEY-----"

    const publicKey = l1 + l2 + l3

    const signature = "MEYCIQCPfWhpzxMqu3gZWflBm5V0aetgb2/S+SGyGcElaOjgdgIhALaD4lbxVwa8HUUBFOLz+CGvIioDkf9oihSnXHCqh8yV";

    console.log(verify.verify(publicKey, signature));// Prints: true or false

2 个答案:

答案 0 :(得分:1)

请参阅this StackOverflow post的更全面的解决方案,该解决方案展示了如何在node.js中使用verify.update()verify.verify()方法。

答案 1 :(得分:0)

这里是如何与Nodejs.Crypto进行积分的方法。首先,需要生成RSA私钥和公钥。有几种方法可以做到这一点,这是一种online with encrypt.JS方法。在将私钥和公钥存储到文件系统后,您可以在下面使用getSignatureByInput函数,该系统在给定字符串输入的情况下生成唯一的签名:

const crypto = require('crypto')
const fs = require('fs')

const getSignatureByInput = (input) => {
  let privatePem = fs.readFileSync('PRIVATE_KEY_FILE_PATH_GOES_HERE')
  let key = privatePem.toString('ascii')
  let sign = crypto.createSign('RSA-SHA256')
  sign.update(input)
  let signature = sign.sign(key, 'hex')

  return signature
}

此后,对于verify a signature,您可以使用以下功能:

const getSignatureVerifyResult = (input) => {
        let signatureSignedByPrivateKey = getSignatureByInput(input)

        let pem = fs.readFileSync('PUBLIC_KEY_FILE_PATH_GOES_HERE')
        let publicKey = pem.toString('ascii')
        const verifier = crypto.createVerify('RSA-SHA256')

        verifier.update(input, 'ascii')

        const publicKeyBuf = new Buffer(publicKey, 'ascii')
        const signatureBuf = new Buffer(signatureSignedByPrivateKey, 'hex')
        const result = verifier.verify(publicKeyBuf, signatureBuf)

        return result;
}

getSignatureVerifyResult将根据签名是否经过验证返回true / false。请记住,在签名时有plethora of algorithms to choose