【发布时间】:2015-07-22 11:23:41
【问题描述】:
我有一个带有消息和私钥的字符串。我需要编写一些 C# 代码,可以使用 RSASSA-PKCS1-v1_5 签名对该字符串进行签名。
您对我应该从哪里着手完成这项工作有任何提示或建议吗? .NET 或可用库中是否有现有的 API 可以执行此操作?
【问题讨论】:
-
稍微改写问题。
我有一个带有消息和私钥的字符串。我需要编写一些 C# 代码,可以使用 RSASSA-PKCS1-v1_5 签名对该字符串进行签名。
您对我应该从哪里着手完成这项工作有任何提示或建议吗? .NET 或可用库中是否有现有的 API 可以执行此操作?
【问题讨论】:
这是一个如何做的例子,你可以在你的代码中进行必要的修改来实现它(例子来自MSDN Site:
using System;
using System.Security.Cryptography;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Parameters;
class RSASample
{
const string PubKeyFile = @"c:\encrypt\fileWithKey.pem";
const string keyName = "Key01";
CspParameters cspp = new CspParameters();
RSAParameters RSAKeyInfo = new RSAParameters();
Org.BouncyCastle.Utilities.IO.Pem.PemObject po = null;
using (StreamReader sr = new StreamReader(PubKeyFile))
{
Org.BouncyCastle.OpenSsl.PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader(reader);
po = pr.ReadPemObject();
}
RSAKeyInfo.Modulus = po.Content;
cspp.KeyContainerName = keyName;
try
{
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp))
{
rsa.PersistKeyInCsp = true;
rsa.ImportParameters(RSAKeyInfo);
//The hash to sign.
byte[] hash;
using (SHA256 sha256 = SHA256.Create())
{
byte[] data = new byte[] { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };
hash = sha256.ComputeHash(data);
}
//Create an RSASignatureFormatter object and pass it the
//RSACryptoServiceProvider to transfer the key information.
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsa);
//Set the hash algorithm to SHA256.
RSAFormatter.SetHashAlgorithm("SHA256");
//Create a signature for HashValue and return it.
byte[] SignedHash = RSAFormatter.CreateSignature(hash);
}
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}
【讨论】: