简体   繁体   中英

Verifying a RSA signature made by Crypto Node.JS in C#

I'm trying to build a web service using Express/NodeJS which signs a piece of information. The signed data is received and verified by a client written in C# . You'll have to forgive my inexperience in cryptography and its associated technologies.

First off, I generate a certificate for the C# client and a private key for the NodeJS application using OpenSSL ;

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

In the NodeJS application , I have the following code;

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

var pem = fs.readFileSync('./keys/key.pem');
var key = pem.toString('ascii');
var privateKey = crypto.createPrivateKey({
    'key': key,
    'format': 'pem',
    'passphrase': '<PASSPHRASE>',
});

function sign(identifier){
    var sign = crypto.createSign('RSA-SHA256');
    sign.update(identifier);
    var sig = sign.sign(privateKey, 'base64');
    return sig;
}

exports.sign = sign;

In this case, the parameter identifier is the data to be signed. The client will receive this, and the signature generated, sig .

In the C# client I have the following snippet;

X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(pub));
using (var sha256 = SHA256.Create())
{
    using (var rsa = cert.GetRSAPublicKey())
    {
        bool results = rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        Console.WriteLine(results.ToString());
    }
}

The pub is the generated certificate in Base64, it is stored in a const string . The data contains the same information as identifier in the NodeJS application, but it's converted to bytes using Convert.FromBase64String(...) , and likewise the signature is the data returned from sig in the NodeJS application, only converted from Base64 to byte data.

When all information is inserted, VerifyData() returns false, this leads me to believe that there's some kind of missmatch between the cryptographic configurations of the web service and the client.

Any ideas?

As pointed out in the comments, the problem was that data in the C# client was converted to from Base64 when the data in the NodeJS application read from UTF-8.

The solution was to convert the string using Encoding.UTF8.GetBytes()

Thanks for the quick response!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM