以下函数使用证书对其进行签名和验证。
private static bool Sign_Verify(X509Certificate2 x509, byte[] random_data)
{
//
// Local variable definitions
//
bool isVerified = false;
byte[] buffer = Encoding.Default.GetBytes("Hello World ... !");
byte[] signature_Data = null;
byte[] signature_Hash = null;
//
// Retrieve the private key of the certificate selected.
//
RSACryptoServiceProvider privateKey
= x509.PrivateKey as RSACryptoServiceProvider;
if (null == privateKey)
{
Console.WriteLine("Invalid Private Key");
} // if
else
{
Console.WriteLine("Certificate has private key.");
} // else
HashAlgorithm hashAlgo = HashAlgorithm.Create("SHA256");
byte[] hash = hashAlgo.ComputeHash(random_data);
//
// Perform signing using the private key
try
{
signature_Hash = privateKey.SignHash(
hash,
CryptoConfig.MapNameToOID("SHA256"));
if (null == signature_Hash)
{
Console.WriteLine("Error: SignHash\n\n");
} // if
else
{
Console.WriteLine("Signature_Hash generated......\n\n");
} // else
} // try
catch (CryptographicException)
{
//e.StackTrace();
} // catch
//
// Retrieve the public key of the certificate selected.
//
RSACryptoServiceProvider publicKey
= x509.PublicKey.Key as RSACryptoServiceProvider;
if (null == publicKey)
{
Console.WriteLine("Invalid Public Key");
} // if
else
{
Console.WriteLine("Certificate has public key.");
} // else
isVerified = publicKey.VerifyHash(
hash,
CryptoConfig.MapNameToOID("SHA256"),
signature_Hash);
if (false == isVerified)
{
Console.WriteLine("Signature of Hash verification failed.");
} // if
else
{
Console.WriteLine("Signature of Hash verified successfully.");
} // else
return isVerified;
} // Sign_Verify 在HashAlgorithm.Create(“SHA256”)中,我们对签名哈希算法的名称进行了硬编码。如何获得证书的签名散列算法的名称而不是硬编码?
发布于 2016-03-29 09:25:44
在.NET中,从证书中获取签名哈希算法似乎并不容易。
cert.SignatureAlgorithm.Value;然后,您需要以某种方式将该OID (例如,SHA256与RSA加密)映射到OID或只是散列算法的名称,而不需要加密(只有SHA256)。您可以自己构建这样的地图,也可以使用现有的地图,例如Bouncy城堡库有一个。不幸的是,它包含在内部类中,因此您必须使用一些反射来实现它。因此,首先添加对Bouncy城堡的引用(通过nuget),然后:
var mapField = typeof(Org.BouncyCastle.Cms.CmsSignedData).Assembly.GetType("Org.BouncyCastle.Cms.CmsSignedHelper").GetField("digestAlgs", BindingFlags.Static | BindingFlags.NonPublic);
var map = (System.Collections.IDictionary) mapField.GetValue(null);这将获取内部digestAlgs类的私有CmsSignedHelper字段的值,该字段仅包含所需的映射。
那你就做:
var hashAlgName = (string)map[cert.SignatureAlgorithm.Value];// returns "SHA256" for OID of sha256 with RSA.
var hashAlg = HashAlgorithm.Create(hashAlgName); // your SHA256https://stackoverflow.com/questions/36277604
复制相似问题