使用BouncyCastle验证在C#中使用ECDSA(使用SHA256)签名的XMLSignature会抛出InvalidCastException

时间:2012-06-16 13:52:31

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

我必须验证使用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应用程序创建),我很确定错误在前面的代码块中。 谁能给我一个提示如何继续?

谢谢, 菲利普

1 个答案:

答案 0 :(得分:0)

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