Search in sources :

Example 11 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class ProcessingInstructionTest method testProcessingInstruction.

@org.junit.Test
public void testProcessingInstruction() throws Exception {
    String signatureFileName = dir + "upp_sign.xml";
    DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
    File f = new File(signatureFileName);
    Document doc = db.parse(new FileInputStream(f));
    Node obj = doc.getElementsByTagNameNS("http://uri.etsi.org/01903/v1.3.2#", "QualifyingProperties").item(0);
    while (obj != null) {
        if (obj instanceof Element) {
            Attr attr = ((Element) obj).getAttributeNode("Id");
            if (attr != null) {
                ((Element) obj).setIdAttributeNode(attr, true);
            }
        }
        obj = obj.getFirstChild();
    }
    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);
    String baseUri = new File(".").toURI().toURL().toString();
    XMLSignature signature = new XMLSignature(sigElement, baseUri);
    signature.addResourceResolver(FileResolver.getInstance());
    X509Certificate cert = signature.getKeyInfo().getX509Certificate();
    if (!signature.checkSignatureValue(cert)) {
        throw new Exception("Signature is invalid!");
    }
}
Also used : XPath(javax.xml.xpath.XPath) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) FileInputStream(java.io.FileInputStream) Attr(org.w3c.dom.Attr) X509Certificate(java.security.cert.X509Certificate) URISyntaxException(java.net.URISyntaxException) ResourceResolverException(org.apache.xml.security.utils.resolver.ResourceResolverException) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSignature(org.apache.xml.security.signature.XMLSignature) File(java.io.File)

Example 12 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class XmlSecTest method checkXmlSignatureSoftwareStack.

private void checkXmlSignatureSoftwareStack(boolean cert) throws Exception {
    Init.init();
    DocumentBuilder documentBuilder = XMLUtils.createDocumentBuilder(false);
    Document testDocument = documentBuilder.newDocument();
    Element rootElement = testDocument.createElementNS("urn:namespace", "tns:document");
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:namespace");
    testDocument.appendChild(rootElement);
    Element childElement = testDocument.createElementNS("urn:childnamespace", "t:child");
    childElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:t", "urn:childnamespace");
    childElement.appendChild(testDocument.createTextNode("hello world"));
    rootElement.appendChild(childElement);
    PrivateKey privateKey;
    PublicKey publicKey = null;
    X509Certificate signingCert = null;
    if (cert) {
        // get key & self-signed certificate from keystore
        String fs = System.getProperty("file.separator");
        FileInputStream fis = new FileInputStream(BASEDIR + fs + "src/test/resources" + fs + "test.jks");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(fis, "changeit".toCharArray());
        signingCert = (X509Certificate) ks.getCertificate("mullan");
        publicKey = signingCert.getPublicKey();
        privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray());
    } else {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(1024);
        KeyPair keyPair = kpg.generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();
    }
    XMLSignature signature = new XMLSignature(testDocument, "", XMLSignature.ALGO_ID_SIGNATURE_DSA, Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
    Element signatureElement = signature.getElement();
    rootElement.appendChild(signatureElement);
    Transforms transforms = new Transforms(testDocument);
    XPathContainer xpath = new XPathContainer(testDocument);
    xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
    xpath.setXPath("not(ancestor-or-self::ds:Signature)");
    transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns());
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1);
    if (cert) {
        signature.addKeyInfo(signingCert);
    } else {
        signature.addKeyInfo(publicKey);
    }
    Element nsElement = testDocument.createElementNS(null, "nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    signature.sign(privateKey);
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xPath = xpf.newXPath();
    xPath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//ds:Signature[1]";
    Element sigElement = (Element) xPath.evaluate(expression, testDocument, XPathConstants.NODE);
    XMLSignature signatureToVerify = new XMLSignature(sigElement, "");
    boolean signResult = signatureToVerify.checkSignatureValue(publicKey);
    assertTrue(signResult);
}
Also used : XPath(javax.xml.xpath.XPath) KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) KeyPairGenerator(java.security.KeyPairGenerator) Document(org.w3c.dom.Document) KeyStore(java.security.KeyStore) XPathContainer(org.apache.xml.security.transforms.params.XPathContainer) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) XMLSignature(org.apache.xml.security.signature.XMLSignature) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext)

Example 13 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext 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 14 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class BaltimoreEncTest method retrieveCCNumber.

/**
 * Method retrieveCCNumber
 *
 * Retrieve the credit card number from the payment info document
 *
 * @param doc The document to retrieve the card number from
 * @return The retrieved credit card number
 * @throws XPathExpressionException
 */
private static String retrieveCCNumber(Document doc) throws javax.xml.transform.TransformerException, XPathExpressionException {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    Map<String, String> namespace = new HashMap<>();
    namespace.put("x", "urn:example:po");
    DSNamespaceContext context = new DSNamespaceContext(namespace);
    xpath.setNamespaceContext(context);
    String expression = "//*[local-name()='Number']";
    Node ccnumElt = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
    if (ccnumElt != null) {
        return ccnumElt.getTextContent();
    }
    return null;
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) HashMap(java.util.HashMap) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) Node(org.w3c.dom.Node)

Example 15 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class DecryptionTest method encryptUsingDOM.

/**
 * Encrypt the document using DOM APIs and run some tests on the encrypted Document.
 */
private void encryptUsingDOM(String algorithm, SecretKey secretKey, String keyTransportAlgorithm, Key wrappingKey, KeyInfo encryptedKeyKeyInfo, Document document, List<String> localNames, boolean content) throws Exception {
    XMLCipher cipher = XMLCipher.getInstance(algorithm);
    cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    if (wrappingKey != null) {
        XMLCipher newCipher = XMLCipher.getInstance(keyTransportAlgorithm);
        newCipher.init(XMLCipher.WRAP_MODE, wrappingKey);
        EncryptedKey encryptedKey = newCipher.encryptKey(document, secretKey);
        if (encryptedKeyKeyInfo != null) {
            encryptedKey.setKeyInfo(encryptedKeyKeyInfo);
        }
        EncryptedData builder = cipher.getEncryptedData();
        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(document);
            builderKeyInfo.getElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dsig", "http://www.w3.org/2000/09/xmldsig#");
            builder.setKeyInfo(builderKeyInfo);
        }
        builderKeyInfo.add(encryptedKey);
    }
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    for (String localName : localNames) {
        String expression = "//*[local-name()='" + localName + "']";
        Element elementToEncrypt = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
        Assert.assertNotNull(elementToEncrypt);
        document = cipher.doFinal(document, elementToEncrypt, content);
    }
    NodeList nodeList = document.getElementsByTagNameNS(XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(), XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart());
    Assert.assertTrue(nodeList.getLength() > 0);
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) KeyInfo(org.apache.xml.security.keys.KeyInfo) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData)

Aggregations

XPath (javax.xml.xpath.XPath)37 XPathFactory (javax.xml.xpath.XPathFactory)37 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)37 Element (org.w3c.dom.Element)23 XMLSignature (org.apache.xml.security.signature.XMLSignature)18 Document (org.w3c.dom.Document)18 NodeList (org.w3c.dom.NodeList)14 ByteArrayInputStream (java.io.ByteArrayInputStream)11 InputStream (java.io.InputStream)11 DocumentBuilder (javax.xml.parsers.DocumentBuilder)11 KeyInfo (org.apache.xml.security.keys.KeyInfo)8 Node (org.w3c.dom.Node)8 File (java.io.File)7 X509Certificate (java.security.cert.X509Certificate)7 Transforms (org.apache.xml.security.transforms.Transforms)7 PublicKey (java.security.PublicKey)6 HashMap (java.util.HashMap)6 XMLCipher (org.apache.xml.security.encryption.XMLCipher)6 FileInputStream (java.io.FileInputStream)5 KeyStore (java.security.KeyStore)5