Node.js:加密签名不一致(每个测试都不同)

ut6juiuv  于 2023-01-25  发布在  Node.js
关注(0)|答案(1)|浏览(168)

我正在尝试对一个有效负载进行签名,并在此处记录的服务文档中重新创建预期的签名:https://paybis.readme.io/reference/partner-api#signing-requests
我的签名实现是:

const signRequest = (privateKey: Buffer) => {

    const verifiableData = '{"event":"VERIFICATION_STATUS_UPDATED","data":{"partnerUserId":"e18fb964-fd9a-4de7-96c4-1lclszzd","status":"started"},"timestamp":1654073212}'

    const signature = crypto.sign(
        'sha512',
        Buffer.from(verifiableData),
        {
            key: privateKey,
            padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
        },
    );

    return signature.toString("base64");
}

我的测试:

const privateKey = fs.readFileSync(path.resolve(__dirname, './private.key'));

const signature = signRequest(privateKey);
const signature2 = signRequest(privateKey);

expect(signature).to.equal(signature2); //FAILS

其中私钥的格式如下:

-----BEGIN RSA PRIVATE KEY-----
MIIJKQIBAAKCAgEAtJWQWnZJqbbxz1wNr3Dn/9I43z4Ddm/jd4G+PCkNGYXcqVqX
...
ukzH0Cx/iuONcUrYtpirM9ZMotfyyl4xO0Hc9bD/I97xn93GOvKFBkV9l7hW
-----END RSA PRIVATE KEY-----

无论我做什么,签名都不一致(又名。每次尝试都会变化)
有人能指出我可能做错了什么吗?
我尝试使用字符串作为可验证体,将密钥保存为.pem文件,将私钥示例化为字符串,并将其作为Buffer和string传递给函数。

2vuwiymt

2vuwiymt1#

正如其中一条评论所述,答案是RSA-PSS是不确定的,因此签名在设计上将 * 不 * 相同。
但是,当尝试使用crypto.verify验证这些不同的正确签名中的任何一个时,它确实按预期进行了验证:

it(`Can create correctly encrypt body`, async function () {
        const privateKey = process.env.PAYBIS_RSA_PRIVATE_KEY!;

        const publicKey = KEY1;

        const wrongPublicKey = KEY2;

        const requestBody = { ... };

        const signature = signRequest(requestBody, privateKey); // Signature here is always different

        const verified = verifySignature(requestBody, signature, publicKey);
        const verifiedFalse = verifySignature(requestBody, signature, wrongPublicKey); 

        expect(verified).to.equal(true, 'Could not verify correct signature'); //Correctly outputs true

        expect(verifiedFalse).to.equal(false, 'Verified incorrect signature'); //Correctly outputs false
    });

相关问题