Search in sources :

Example 31 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project santuario-java by apache.

the class CreateSignatureTest method testCanonicalizedOctetStream.

@org.junit.Test
public void testCanonicalizedOctetStream() throws Exception {
    String signedXML = doSign();
    Document doc = null;
    try (InputStream is = new ByteArrayInputStream(signedXML.getBytes())) {
        doc = db.parse(is);
    }
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//ds:Signature[1]";
    Element sigElement = (Element) xpath.evaluate(expression, doc, XPathConstants.NODE);
    XMLSignature signature = new XMLSignature(sigElement, "");
    KeyInfo ki = signature.getKeyInfo();
    if (ki == null) {
        throw new RuntimeException("No keyinfo");
    }
    PublicKey pk = signature.getKeyInfo().getPublicKey();
    if (pk == null) {
        throw new RuntimeException("No public key");
    }
    SignedInfo si = signature.getSignedInfo();
    SignatureAlgorithm sa = si.getSignatureAlgorithm();
    sa.initVerify(pk);
    byte[] sigBytes = signature.getSignatureValue();
    byte[] canonicalizedBytes = si.getCanonicalizedOctetStream();
    sa.update(canonicalizedBytes, 0, canonicalizedBytes.length);
    assertTrue(sa.verify(sigBytes));
    assertTrue(si.verify(false));
}
Also used : XPath(javax.xml.xpath.XPath) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) Document(org.w3c.dom.Document) SignedInfo(org.apache.xml.security.signature.SignedInfo) XPathFactory(javax.xml.xpath.XPathFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) KeyInfo(org.apache.xml.security.keys.KeyInfo) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Example 32 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project santuario-java by apache.

the class HMACOutputLengthTest method test_generate_hmac_sha1_40.

@org.junit.Test
public void test_generate_hmac_sha1_40() throws Exception {
    Document doc = XMLUtils.createDocumentBuilder(false).newDocument();
    XMLSignature sig = new XMLSignature(doc, null, XMLSignature.ALGO_ID_MAC_HMAC_SHA1, 40, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    try {
        sig.sign(getSecretKey("secret".getBytes(StandardCharsets.US_ASCII)));
        fail("Expected HMACOutputLength Exception");
    } catch (XMLSignatureException xse) {
        // System.out.println(xse.getMessage());
        if (!xse.getMsgID().equals("algorithms.HMACOutputLengthMin")) {
            fail(xse.getMessage());
        }
    }
}
Also used : XMLSignature(org.apache.xml.security.signature.XMLSignature) Document(org.w3c.dom.Document) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException)

Example 33 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project santuario-java by apache.

the class KeyValueTest method testDSAPublicKey.

@org.junit.Test
public void testDSAPublicKey() throws Exception {
    File f = null;
    String filename = "src/test/resources/ie/baltimore/merlin-examples/merlin-xmldsig-twenty-three/signature-enveloping-dsa.xml";
    if (BASEDIR != null && !"".equals(BASEDIR)) {
        f = new File(BASEDIR + SEP + filename);
    } else {
        f = new File(filename);
    }
    Document doc = db.parse(new FileInputStream(f));
    NodeList nl = doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature");
    XMLSignature sig = new XMLSignature((Element) nl.item(0), f.toURI().toURL().toString());
    KeyInfo ki = sig.getKeyInfo();
    KeyValue kv = ki.itemKeyValue(0);
    PublicKey pk = kv.getPublicKey();
    assertNotNull(pk);
}
Also used : KeyValue(org.apache.xml.security.keys.content.KeyValue) KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLSignature(org.apache.xml.security.signature.XMLSignature) PublicKey(java.security.PublicKey) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 34 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project santuario-java by apache.

the class SignatureVerificationReferenceURIResolverTest method testSignatureVerificationWithSameDocumentXPointerIdDoubleQuoteReference.

@Test
public void testSignatureVerificationWithSameDocumentXPointerIdDoubleQuoteReference() throws Exception {
    // Read in plaintext document
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(sourceDocument);
    // Set up the Key
    KeyStore keyStore = KeyStore.getInstance("jks");
    keyStore.load(this.getClass().getClassLoader().getResource("transmitter.jks").openStream(), "default".toCharArray());
    Key key = keyStore.getKey("transmitter", "default".toCharArray());
    X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//*[local-name()='ShippingAddress']";
    Element elementToSign = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
    Assert.assertNotNull(elementToSign);
    String id = UUID.randomUUID().toString();
    elementToSign.setAttributeNS(null, "Id", id);
    elementToSign.setIdAttributeNS(null, "Id", true);
    // Sign using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    ReferenceInfo referenceInfo = new ReferenceInfo("#xpointer(id(\"" + id + "\"))", new String[] { "http://www.w3.org/2001/10/xml-exc-c14n#" }, "http://www.w3.org/2000/09/xmldsig#sha1", false);
    List<ReferenceInfo> referenceInfos = new ArrayList<>();
    referenceInfos.add(referenceInfo);
    XMLSignature sig = signUsingDOM("http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos);
    // Add KeyInfo
    sig.addKeyInfo(cert);
    // Convert Document to a Stream Reader
    javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(document), new StreamResult(baos));
    XMLStreamReader xmlStreamReader = null;
    try (InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
    }
    // Verify signature
    XMLSecurityProperties properties = new XMLSecurityProperties();
    properties.setSignatureVerificationKey(cert.getPublicKey());
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
    StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) XPathFactory(javax.xml.xpath.XPathFactory) XMLSignature(org.apache.xml.security.signature.XMLSignature) XPath(javax.xml.xpath.XPath) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InboundXMLSec(org.apache.xml.security.stax.ext.InboundXMLSec) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSecurityProperties(org.apache.xml.security.stax.ext.XMLSecurityProperties) Key(java.security.Key) Test(org.junit.Test)

Example 35 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project santuario-java by apache.

the class SignatureVerificationReferenceURIResolverTest method testSignatureVerificationWithExternalFilesystemXMLReference.

@Test
public void testSignatureVerificationWithExternalFilesystemXMLReference() throws Exception {
    // Read in plaintext document
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(sourceDocument);
    // Set up the Key
    KeyStore keyStore = KeyStore.getInstance("jks");
    keyStore.load(this.getClass().getClassLoader().getResource("transmitter.jks").openStream(), "default".toCharArray());
    Key key = keyStore.getKey("transmitter", "default".toCharArray());
    X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
    // Sign using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    File file = new File(BASEDIR + "/src/test/resources/ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml").getCanonicalFile();
    ReferenceInfo referenceInfo = new ReferenceInfo(file.toURI().toString(), new String[] { "http://www.w3.org/2001/10/xml-exc-c14n#" }, "http://www.w3.org/2000/09/xmldsig#sha1", false);
    List<ReferenceInfo> referenceInfos = new ArrayList<>();
    referenceInfos.add(referenceInfo);
    XMLSignature sig = signUsingDOM("http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos);
    // Add KeyInfo
    sig.addKeyInfo(cert);
    // Convert Document to a Stream Reader
    javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(document), new StreamResult(baos));
    XMLStreamReader xmlStreamReader = null;
    try (InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
    }
    // Verify signature
    XMLSecurityProperties properties = new XMLSecurityProperties();
    properties.setSignatureVerificationKey(cert.getPublicKey());
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
    try {
        TestUtils.switchAllowNotSameDocumentReferences(true);
        StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
    } finally {
        TestUtils.switchAllowNotSameDocumentReferences(false);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InboundXMLSec(org.apache.xml.security.stax.ext.InboundXMLSec) Document(org.w3c.dom.Document) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLSignature(org.apache.xml.security.signature.XMLSignature) XMLSecurityProperties(org.apache.xml.security.stax.ext.XMLSecurityProperties) File(java.io.File) Key(java.security.Key) Test(org.junit.Test)

Aggregations

XMLSignature (org.apache.xml.security.signature.XMLSignature)137 Document (org.w3c.dom.Document)92 Element (org.w3c.dom.Element)69 X509Certificate (java.security.cert.X509Certificate)60 Test (org.junit.Test)60 DocumentBuilder (javax.xml.parsers.DocumentBuilder)52 InputStream (java.io.InputStream)51 ByteArrayInputStream (java.io.ByteArrayInputStream)50 ByteArrayOutputStream (java.io.ByteArrayOutputStream)49 KeyStore (java.security.KeyStore)48 ArrayList (java.util.ArrayList)48 XMLStreamReader (javax.xml.stream.XMLStreamReader)43 Key (java.security.Key)42 DOMSource (javax.xml.transform.dom.DOMSource)42 StreamResult (javax.xml.transform.stream.StreamResult)42 Transforms (org.apache.xml.security.transforms.Transforms)29 SecretKey (javax.crypto.SecretKey)28 XPath (javax.xml.xpath.XPath)23 KeyInfo (org.apache.xml.security.keys.KeyInfo)22 XPathFactory (javax.xml.xpath.XPathFactory)19