简体   繁体   English

检查x509证书的签名

[英]Check signature for x509 certificate

I have: 我有:

  1. x509 certificate (Base64); x509证书(Base64);
  2. String data; 字符串数据;
  3. Signature of string data (Base64). 字符串数据的签名(Base64)。

Is it possible to check signature? 是否可以检查签名?

My code: 我的代码:

  bool valid = false;

  var signature = Convert.FromBase64String(base64Signature);
  var data = Encoding.UTF8.GetBytes(stringData);

  var x509 = new X509Certificate2(Convert.FromBase64String(certificate));
  var dsa = x509.PublicKey.Key as DSACryptoServiceProvider;
  if (dsa!=null)
    valid = dsa.VerifySignature(data, signature);
  else {
    var rsa = x509.PublicKey.Key as RSACryptoServiceProvider;
    if (rsa!=null)
      valid = rsa.VerifyHash(data, ???, signature);
  }

I don't know what I should use instead of ???. 我不知道应该用什么而不是???。 It is possible to get hash algorithm from certificate? 可以从证书中获取哈希算法吗?

The sender of the original message may use whatever algorithm he likes to sign his message, using the private key that corresponds to the certificate. 原始消息的发送者可以使用他喜欢的任何算法来使用与证书相对应的私钥来签署他的消息。 While you can get the OID of the algorithm used to sign the certificate from its the SignatureAlgorithm property, nothing prevents the sender to use a different signing or hashing algorithm. 虽然您可以从SignatureAlgorithm属性获取用于对证书进行签名的算法的OID,但没有任何东西可以阻止发件人使用其他签名或散列算法。

According to the documentation , the only valid hashing algorithms for the RSA provider are SHA1 and MD5. 根据文档 ,RSA提供程序唯一有效的哈希算法是SHA1和MD5。 Perhaps you should try VerifyHash with both algorithms and check which one succeeds. 也许您应该使用两种算法尝试VerifyHash并检查哪一个成功。 You can get the proper OID for each one using the CryptoConfig.MapNameToOID method like this: 您可以使用CryptoConfig.MapNameToOID方法为每个方法获取正确的OID,如下所示:

string sha1Oid = CryptoConfig.MapNameToOID("SHA1");
string md5Oid = CryptoConfig.MapNameToOID("MD5");
bool sha1Valid = rsa.VerifyHash(data, sha1Oid, signature);
bool md5Valid = rsa.VerifyHash(data, md5Oid, signature);
valid = sha1Valid || md5Valid;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM