在.NET上使用RSA私钥签名字符串?

时间:2010-07-03 00:36:39

标签: c# rsa bouncycastle der

byte[] plaintext = System.Text.Encoding.UTF8.GetBytes("AAAAAAAAAAAAA");

TextReader trCer = new StreamReader(@"AA.key"); //key in PEM format

PemReader rdCer = new PemReader(trCer);

AsymmetricCipherKeyPair o = rdCer.ReadObject() as AsymmetricCipherKeyPair;

ISigner sig = SignerUtilities.GetSigner("MD5WithRSAEncryption");

sig.Init(true, o.Private);

sig.BlockUpdate(plaintext,0,plaintext.Length);

Byte[] signature  = sig.GenerateSignature();

string signatureHeader = Convert.ToBase64String(signature);

Console.WriteLine(signatureHeader);

如何使用DER格式的密钥? 我正在使用库BouncyCastle.Crypto.dll

`

1 个答案:

答案 0 :(得分:1)

您应该使用 derpem 文件转换为 OpenSsl 文件:

openssl x509 -inform der -in certificate.cer -out certificate.pem

然后使用 pemBountyCastle 生成符号,如下所示:

using (var rsa = new RSACryptoServiceProvider())
            {
                var privateKey = new StringBuilder();
                privateKey.AppendLine("-----BEGIN RSA PRIVATE KEY-----");
                privateKey.AppendLine(_config.Value.PrivateKey);
                privateKey.AppendLine("-----END RSA PRIVATE KEY-----");

                var pem = new PemReader(new StringReader(privateKey.ToString()));
                var keyPair = (AsymmetricCipherKeyPair)pem.ReadObject();
                var privateKeyParameters = (RsaPrivateCrtKeyParameters)keyPair.Private;
                var rsaParameters = DotNetUtilities.ToRSAParameters(privateKeyParameters);

                rsa.ImportParameters(rsaParameters);
                var sign = rsa.SignData(Encoding.UTF8.GetBytes(data), new HashAlgorithmName("SHA1"),
                    RSASignaturePadding.Pkcs1);

                return Convert.ToBase64String(sign);
            }

以上截取的代码使用私钥作为字符串,我将其包装成 pem 格式。