【问题标题】:Verifying XMLSignature signed with ECDSA (with SHA256) in C# using BouncyCastle throws InvalidCastException使用 BouncyCastle 在 C# 中验证使用 ECDSA(使用 SHA256)签名的 XMLSignature 会引发 InvalidCastException
【发布时间】:2012-06-16 13:52:30
【问题描述】:

我必须验证使用http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256 算法签名的 XmlSignature。由于使用本机 .NET SignedXml 类不支持此算法,因此我使用 BouncyCastle 实现了检查。

我的实现如下:

// read certificate
var bytes = Convert.FromBase64String("...");
var cert = new X509CertificateParser().ReadCertificate(bytes);
var ecPublicKeyParameters = (ECPublicKeyParameters)cert.GetPublicKey();

// load signed XmlDocument
var xDoc = new XmlDocument();
xDoc.Load("Response_Success.xml");

// get signature value
var nav = xDoc.CreateNavigator();
nav.MoveToFollowing("SignatureValue", "http://www.w3.org/2000/09/xmldsig#");
var signatureAsString = Regex.Replace(nav.InnerXml.Trim(), @"\s", "");
var signatureValue = Convert.FromBase64String(signatureAsString);

// get and canonicalize signed info
var signedInfo = xDoc.GetElementsByTagName("SignedInfo", "http://www.w3.org/2000/09/xmldsig#")[0];
// move used NS from the document root element to the SignedInfo element
var ns = RetrieveNameSpaces((XmlElement)signedInfo);
InsertNamespacesIntoElement(ns, (XmlElement)signedInfo);

// apply an XmlDsigC14NTransformation
var signedInfoStream = canonicalizeNode(signedInfo);

// hash signed info
var hashAlgorithm = SHA256.Create();
var hashedSignedInfo = hashAlgorithm.ComputeHash(signedInfoStream);

// check signature
var signer = SignerUtilities.GetSigner("ECDSA");
signer.Init(false, ecPublicKeyParameters);
signer.BlockUpdate(hashedSignedInfo, 0, hashedSignedInfo.Length);
var isSignatureValid = signer.VerifySignature(signatureValue);

错误发生在最后一条语句中

System.InvalidCastException: Unable to cast object of type 'Org.BouncyCastle.Asn1.DerApplicationSpecific' to type 'Org.BouncyCastle.Asn1.Asn1Sequence'.

由于 XmlSignature 很可能是有效的(由官方认可的协会使用 Java 应用程序创建),我很确定错误出在前面的代码块中。 谁能给我一个提示如何进行?

谢谢, 菲利普

【问题讨论】:

    标签: c# digital-signature bouncycastle xml-signature


    【解决方案1】:

    你编码对了吗?您可能想看看以下内容: Digital Signature Verification using BouncyCastle - ECDSA with SHA 256, C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2020-07-11
      • 2014-10-05
      相关资源
      最近更新 更多