下面的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));
}