The following code in python is my baseline that I need to implement using .net core
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
import base64
thing_to_sign = "12345"
key = RSA.importKey(open('dev.private.pem').read())
signer = PKCS1_v1_5.new(key)
data = SHA256.new(thing_to_sign)
signedData = signer.sign(data)
sig = base64.b64encode(signedData)
print sig
for now i have tried to do the same with BouncyCastel but got a different result than i should.
var data = "12345";
var keyParams = ReadAsymmetricKeyParameter("dev.private.pem");
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
encryptEngine.Init(true, keyParams);
var dataBytes = GetSHA256Bytes(data);
var signedData = encryptEngine.ProcessBlock(dataBytes, 0, dataBytes.Length);
var sig64 = Convert.ToBase64String(signedData);
const string expectedSig = "MEka+7qTARRoXWmU4nm6sBc9R8908AIx.... shorten for reading convinience";
Assert.Equal(expectedSig, sig64); //Fails here the result is differnt the python code :(
the ReadAsymmetricKeyParameter
method:
private AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
var fileStream = File.OpenText(pemFilename);
var pemReader = new PemReader(fileStream);
var keyParameter = (AsymmetricCipherKeyPair) pemReader.ReadObject();
return keyParameter.Private;
}
Then i figured that the Pkcs1Encoding
might not be 1.5 as it should and could not find enougth infor about it so im trying to revert to use System.Security.Cryptography
from the .Net Framework but stuck at how to load the private pem key file
var dataStr = "12345";
using (var rsa = new RSACryptoServiceProvider())
{
var data = GetSHA256Bytes(dataStr);
var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
rsaFormatter.SetHashAlgorithm("SHA256");
byte[] SignedHash = rsaFormatter.CreateSignature(data);
var sig64 = Convert.ToBase64String(SignedHash);
}
The GetSHA256Bytes
helper is straightforward:
using (var hash = SHA256.Create())
{
return hash.ComputeHash(Encoding.UTF8.GetBytes(data));
}