2013-05-14 176 views
1

我有一個問題,我無法弄清楚如何解決。 我的應用程序收到(應該是)簽名的XML,我必須驗證它是否正確。 這裏是一個什麼樣的在XML收到XML簽名驗證

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> 
     <SignedInfo> 
      <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> 
      <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> 
      <Reference URI="35121103220612000188550010000000131000009300"> 
       <Transforms> 
        <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /> 
        <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> 
       </Transforms> 
       <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> 
       <DigestValue>uLZ/66r6OoNLpj5v4cIsrv5zmyc=</DigestValue> 
      </Reference> 
     </SignedInfo> 
     <SignatureValue>encoded</SignatureValue> 
     <KeyInfo> 
      <X509Data> 
       <X509Certificate>encoded</X509Certificate> 
      </X509Data> 
     </KeyInfo> 
    </Signature> 

我的一切互聯網上找到驗證需要公鑰對簽名部分。但我沒有。我只有DigestValue。 你知道它是否可以僅使用DiggestValue進行驗證?

這是我到目前爲止。問題是從哪裏獲得關鍵X509KeySelector

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    dbf.setNamespaceAware(true); 
    DocumentBuilder builder = dbf.newDocumentBuilder(); 
    Document doc = builder.parse("/home/test.xml"); 
    Node nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0); 
    DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(publicKey), nl); 
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); 
    XMLSignature signature = factory.unmarshalXMLSignature(valContext); 
    System.out.println(signature.validate(valContext)); 

在此先感謝。

+0

什麼的密鑰信息節?它真的是「編碼」還是別的?我的猜測是它包含你需要的證書。 – jtahlborn 2013-05-14 18:19:10

+0

是的。我把編碼,因爲它是一個大字符串。但它是一個編碼字符串 – Augusto 2013-05-15 03:30:25

回答

5

您從嵌入式X509證書中獲得X509密鑰。

UPDATE:

做了谷歌搜索「XML簽名X509證書」止跌回升this page,這似乎給你所有你需要的答案。

+0

我該怎麼做? – Augusto 2013-05-15 11:59:52

+0

@ACDias - 更新了我的答案 – jtahlborn 2013-05-15 15:42:22

+0

下面是一個工作示例,如果有人需要它:http://snipt.org/EBQ3 – 2014-02-12 13:18:41

0

您可能需要您的DocumentBuilderFactory調用setNamespaceAware(真),否則會拋出以下異常:

Document implementation must support DOM Level 2 and be namespace aware 
0

證書本身包含公鑰:

CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 
InputStream in = new ByteArrayInputStream(Base64.getDecoder().decode(certificateStringFromXml)); 
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in); 
PublicKey pk = cert.getPublicKey();