C#.net核心中带有私钥(.pem文件)的Signig数据字符串

时间:2018-08-01 08:25:15

标签: c# .net .net-core rsa pkcs#1

下面的python代码是我需要使用.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

现在我已经尝试对BouncyCastel进行相同操作,但结果却与我应有的不同。

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 :(

ReadAsymmetricKeyParameter方法:

private AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
    var fileStream = File.OpenText(pemFilename);
    var pemReader = new PemReader(fileStream);
    var keyParameter = (AsymmetricCipherKeyPair) pemReader.ReadObject();
    return keyParameter.Private;
}

然后我发现Pkcs1Encoding可能不应该是1.5,也找不到足够的信息,因此我试图恢复使用.Net Framework中的System.Security.Cryptography,但坚持如何加载私钥pem密钥文件

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);
}

GetSHA256Bytes助手很简单:

        using (var hash = SHA256.Create())
        {
            return hash.ComputeHash(Encoding.UTF8.GetBytes(data));
        }

0 个答案:

没有答案