2017-02-25 47 views
1

如何使用Java StAX API驗證XML上的數字簽名。我已經知道如何使用DOM進行驗證。我有一個非常大的XML文件,我需要一種使用StAX驗證簽名的方法。請幫助...使用StAX驗證數字簽名

回答

0

我發現這個blog post,其中指出了一些代碼演示一個StAX的實現:

要了解如何配置新的入站的基於StAX的XML簽名 功能,看看 測試使用的「verifyUsingStAX」方法。與創建簽名一樣,有必要創建一個XMLSecurityProperties對象,並告訴它要執行什麼「操作」。 另外,你必須調用下面的方法,除非完全 簽名密鑰被包含在簽名的密鑰信息:

  • properties.setSignatureVerificationKey(密鑰) - 要使用的密鑰來驗證 簽名。

https://github.com/coheigea/testcases/blob/master/apache/santuario/santuario-xml-signature/src/test/java/org/apache/coheigea/santuario/xmlsignature/SignatureUtils.java#L201

/** 
    * Verify the document using the StAX API of Apache Santuario - XML Security for Java. 
    */ 
    public static void verifyUsingStAX(
     InputStream inputStream, 
     List<QName> namesToSign, 
     X509Certificate cert 
    ) throws Exception { 
     // Set up the Configuration 
     XMLSecurityProperties properties = new XMLSecurityProperties(); 
     List<XMLSecurityConstants.Action> actions = new ArrayList<XMLSecurityConstants.Action>(); 
     actions.add(XMLSecurityConstants.SIGNATURE); 
     properties.setActions(actions); 

     properties.setSignatureVerificationKey(cert.getPublicKey()); 

     InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties); 

     XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); 
     final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream); 

     TestSecurityEventListener eventListener = new TestSecurityEventListener(); 
     XMLStreamReader securityStreamReader = 
      inboundXMLSec.processInMessage(xmlStreamReader, null, eventListener); 

     while (securityStreamReader.hasNext()) { 
      securityStreamReader.next(); 
     } 
     xmlStreamReader.close(); 
     inputStream.close(); 

     // Check that what we were expecting to be signed was actually signed 
     List<SignedElementSecurityEvent> signedElementEvents = 
      eventListener.getSecurityEvents(SecurityEventConstants.SignedElement); 
     Assert.assertNotNull(signedElementEvents); 

     for (QName nameToSign : namesToSign) { 
      boolean found = false; 
      for (SignedElementSecurityEvent signedElement : signedElementEvents) { 
       if (signedElement.isSigned() 
        && nameToSign.equals(getSignedQName(signedElement.getElementPath()))) { 
        found = true; 
        break; 
       } 
      } 
      Assert.assertTrue(found); 
     } 

     // Check Signing cert 
     X509TokenSecurityEvent tokenEvent = 
      (X509TokenSecurityEvent)eventListener.getSecurityEvent(SecurityEventConstants.X509Token); 
     Assert.assertNotNull(tokenEvent); 

     Assert.assertTrue(tokenEvent.getSecurityToken() instanceof X509SecurityToken); 
     X509SecurityToken x509SecurityToken = (X509SecurityToken)tokenEvent.getSecurityToken(); 
     Assert.assertEquals(x509SecurityToken.getX509Certificates()[0], cert); 
    }