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