我最终解决了这个问题,主要是通过unix终端使用OpenSSL密钥创建,但是如果它对其他人有帮助的话,这里是最终的产品。
用法:
string signature = Signer.SignData(Signer.Canonicalize(version, consumerId, timestamp)[1], _keyManager.Key);
_keyManager.Key
通过使用BouncyCastle读取受密码保护的私钥找到。
StreamReader sr = File.OpenText("c:\key.pem");
PemReader pr = new PemReader(sr, new PasswordFinder("123"));
RsaPrivateCrtKeyParameters keyPair = pr.ReadObject() as RsaPrivateCrtKeyParameters;
return DotNetUtilities.ToRSAParameters(keyPair);
Signer.SignData
实施。
public static string SignData(string message, RSAParameters privateKey)
{
byte[] signedBytes;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
byte[] originalBytes = Encoding.UTF8.GetBytes(message);
try
{
rsa.ImportParameters(privateKey);
signedBytes = rsa.SignData(originalBytes, CryptoConfig.MapNameToOID("SHA256"));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
return Convert.ToBase64String(signedBytes);
}
为了确认它的工作,我使用了公钥来验证。公钥的获取类似于私钥。
public static bool Verify(string originalData, string base64SignedData, RSAParameters publicKey)
{
bool success = false;
byte[] signedBytes = Convert.FromBase64String(base64SignedData);
byte[] bytesToVerify = Encoding.UTF8.GetBytes(originalData);
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
try
{
rsa.ImportParameters(publicKey);
SHA256 sha256 = new SHA256Managed();
byte[] hashedData = sha256.ComputeHash(signedBytes);
success = rsa.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA256"), signedBytes);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
return success;
}
把这一切放在一起作为一个测试:
public void SignTest()
{
// Arrange
string version = "1";
string consumerId = "8644d500-eyue-47gh-9b2b-54d5a4b9d45t";
string timestamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
StreamReader sr = File.OpenText(@"C:\privateKey.pem");
PemReader pr = new PemReader(sr, new PasswordFinder("123"));
RsaPrivateCrtKeyParameters keyPair = (RsaPrivateCrtKeyParameters)pr.ReadObject();
RSAParameters rsaPrivateParameters = DotNetUtilities.ToRSAParameters(keyPair);
StreamReader sr2 = File.OpenText(@"C:\publicKey.pem");
PemReader pr2 = new PemReader(sr2, new PasswordFinder("123"));
var keyPair2 = pr2.ReadObject();
RSAParameters rsaPublicParameters = DotNetUtilities.ToRSAParameters((RsaKeyParameters)keyPair2);
string[] canonicalForm = Signer.Canonicalize(version, consumerId, timestamp);
// Act
string signedData = Signer.SignData(canonicalForm[1], rsaPrivateParameters);
bool validated = Signer.Verify(canonicalForm[1], signedData, rsaPublicParameters);
// Assert
Assert.True(validated);
}