2012-06-16 39 views
2

我必須驗證使用http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256算法簽名的XmlSignature。由於該算法不支持使用本機.NET SignedXml類,因此我使用BouncyCastle實現了該檢查。驗證使用BouncyCastle在C#中使用ECDSA(使用SHA256)簽名的XML簽名InvalidCastException

我的實現原理如下:

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

在最後statment出現的錯誤,並讀取

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

由於XMLSignature中最有可能是有效的(通過使用官方認可的關聯創建Java應用程序)我很確定這個錯誤在前面的代碼塊中。 任何人都可以給我一個提示如何進行?

感謝, 菲利普

回答

相關問題