2

I have to verify an XmlSignature that was signed using the http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256 algorithm. As this algorithm is not supported using the native .NET SignedXml class I've implemented the check using BouncyCastle.

My implementation works as follows:

// 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);

The error occurs in the very last statment and reads

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

As the XmlSignature is most probably valid (created by an officially recognized association using a Java application) I'm pretty sure the mistake is in the preceding code block. Can anyone give me a hint how to proceed?

Thanks, Philipp

4

1 回答 1

0

你编码对了吗?您可能想查看以下内容: 使用 BouncyCastle 进行数字签名验证 - 带有 SHA 256、C# 的 ECDSA

于 2012-11-13T17:22:51.090 回答