Search in sources :

Example 56 with XMLCipher

use of org.apache.xml.security.encryption.XMLCipher in project santuario-java by apache.

the class XMLEncryption11Test method decryptElementDOM.

/**
 * Decrypt using DOM API
 */
private Document decryptElementDOM(Document doc, Key rsaKey) throws Exception {
    // Create the XMLCipher element
    XMLCipher cipher = XMLCipher.getInstance();
    // Need to pre-load the Encrypted Data so we can get the key info
    Element ee = (Element) doc.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData").item(0);
    cipher.init(XMLCipher.DECRYPT_MODE, null);
    EncryptedData encryptedData = cipher.loadEncryptedData(doc, ee);
    KeyInfo ki = encryptedData.getKeyInfo();
    EncryptedKey encryptedKey = ki.itemEncryptedKey(0);
    XMLCipher cipher2 = XMLCipher.getInstance();
    cipher2.init(XMLCipher.UNWRAP_MODE, rsaKey);
    Key key = cipher2.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
    cipher.init(XMLCipher.DECRYPT_MODE, key);
    Document dd = cipher.doFinal(doc, ee);
    return dd;
}
Also used : KeyInfo(org.apache.xml.security.keys.KeyInfo) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Element(org.w3c.dom.Element) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey)

Example 57 with XMLCipher

use of org.apache.xml.security.encryption.XMLCipher in project santuario-java by apache.

the class XMLCipherTest method testSerializedData.

@org.junit.Test
public void testSerializedData() throws Exception {
    if (!haveISOPadding) {
        LOG.warn("Test testSerializedData skipped as necessary algorithms not available");
        return;
    }
    byte[] bits128 = { (byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19, (byte) 0x1A, (byte) 0x1B, (byte) 0x1C, (byte) 0x1D, (byte) 0x1E, (byte) 0x1F };
    Key key = new SecretKeySpec(bits128, "AES");
    // source
    Document d = document();
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    // encrypt
    cipher = XMLCipher.getInstance(XMLCipher.AES_128);
    cipher.init(XMLCipher.ENCRYPT_MODE, key);
    // serialize element ...
    Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    canon.setWriter(baos);
    canon.notReset();
    canon.canonicalizeSubtree(e);
    baos.close();
    String before = baos.toString(StandardCharsets.UTF_8.name());
    byte[] serialized = baos.toByteArray();
    EncryptedData encryptedData = null;
    try (InputStream is = new ByteArrayInputStream(serialized)) {
        encryptedData = cipher.encryptData(d, EncryptionConstants.TYPE_ELEMENT, is);
    }
    // decrypt
    XMLCipher dcipher = XMLCipher.getInstance(XMLCipher.AES_128);
    dcipher.init(XMLCipher.DECRYPT_MODE, key);
    String algorithm = encryptedData.getEncryptionMethod().getAlgorithm();
    assertEquals(XMLCipher.AES_128, algorithm);
    byte[] bytes = dcipher.decryptToByteArray(dcipher.martial(encryptedData));
    String after = new String(bytes, StandardCharsets.UTF_8);
    assertEquals(before, after);
    // test with null type
    try (InputStream is = new ByteArrayInputStream(serialized)) {
        encryptedData = cipher.encryptData(d, null, is);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) XMLCipher(org.apache.xml.security.encryption.XMLCipher) ByteArrayOutputStream(java.io.ByteArrayOutputStream) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) PublicKey(java.security.PublicKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) Canonicalizer(org.apache.xml.security.c14n.Canonicalizer)

Example 58 with XMLCipher

use of org.apache.xml.security.encryption.XMLCipher in project santuario-java by apache.

the class XMLCipherTest method testEecryptToByteArray.

@org.junit.Test
public void testEecryptToByteArray() throws Exception {
    org.junit.Assume.assumeTrue(bcInstalled);
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);
    Key key = keygen.generateKey();
    Document document = document();
    XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_128_GCM);
    cipher.init(XMLCipher.ENCRYPT_MODE, key);
    cipher.getEncryptedData();
    Document encrypted = cipher.doFinal(document, document);
    XMLCipher xmlCipher = XMLCipher.getInstance();
    xmlCipher.init(XMLCipher.DECRYPT_MODE, key);
    Element encryptedData = (Element) encrypted.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);
    xmlCipher.decryptToByteArray(encryptedData);
}
Also used : Element(org.w3c.dom.Element) XMLCipher(org.apache.xml.security.encryption.XMLCipher) Document(org.w3c.dom.Document) KeyGenerator(javax.crypto.KeyGenerator) PublicKey(java.security.PublicKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Example 59 with XMLCipher

use of org.apache.xml.security.encryption.XMLCipher in project santuario-java by apache.

the class XMLCipherTest method testPhysicalRepresentation.

/*
     * Test physical representation of decrypted element, see SANTUARIO-309
     */
@org.junit.Test
public void testPhysicalRepresentation() throws Exception {
    if (haveISOPadding) {
        DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
        byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
        DESedeKeySpec keySpec = new DESedeKeySpec(bits192);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        // Test inherited namespaces don't add extra attributes
        // Test unused namespaces are preserved
        final String DATA1 = "<ns:root xmlns:ns=\"ns.com\"><ns:elem xmlns:ns2=\"ns2.com\">11</ns:elem></ns:root>";
        Document doc = null;
        try (InputStream is = new ByteArrayInputStream(DATA1.getBytes(StandardCharsets.UTF_8))) {
            doc = db.parse(is);
        }
        Element elem = (Element) doc.getDocumentElement().getFirstChild();
        XMLCipher dataCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        dataCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
        dataCipher.doFinal(doc, elem);
        Element encrElem = (Element) doc.getDocumentElement().getFirstChild();
        assertEquals("EncryptedData", encrElem.getLocalName());
        XMLCipher deCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        deCipher.init(XMLCipher.DECRYPT_MODE, secretKey);
        deCipher.doFinal(doc, encrElem);
        Element decrElem = (Element) doc.getDocumentElement().getFirstChild();
        assertEquals("ns:elem", decrElem.getNodeName());
        assertEquals("ns.com", decrElem.getNamespaceURI());
        assertEquals(1, decrElem.getAttributes().getLength());
        Attr attr = (Attr) decrElem.getAttributes().item(0);
        assertEquals("xmlns:ns2", attr.getName());
        assertEquals("ns2.com", attr.getValue());
        // Test default namespace undeclaration is preserved
        final String DATA2 = "<ns:root xmlns=\"defns.com\" xmlns:ns=\"ns.com\"><elem xmlns=\"\">11</elem></ns:root>";
        try (InputStream is = new ByteArrayInputStream(DATA2.getBytes(StandardCharsets.UTF_8))) {
            doc = db.parse(is);
        }
        elem = (Element) doc.getDocumentElement().getFirstChild();
        dataCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        dataCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
        dataCipher.doFinal(doc, elem);
        encrElem = (Element) doc.getDocumentElement().getFirstChild();
        assertEquals("EncryptedData", encrElem.getLocalName());
        deCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        deCipher.init(XMLCipher.DECRYPT_MODE, secretKey);
        deCipher.doFinal(doc, encrElem);
        decrElem = (Element) doc.getDocumentElement().getFirstChild();
        assertEquals("elem", decrElem.getNodeName());
        assertNull(decrElem.getNamespaceURI());
        assertEquals(1, decrElem.getAttributes().getLength());
        attr = (Attr) decrElem.getAttributes().item(0);
        assertEquals("xmlns", attr.getName());
        assertEquals("", attr.getValue());
        // Test comments and PIs are not treated specially when serializing element content.
        // Other c14n algorithms add a newline after comments and PIs, when they are before or after the document element.
        final String DATA3 = "<root><!--comment1--><?pi1 target1?><elem/><!--comment2--><?pi2 target2?></root>";
        try (InputStream is = new ByteArrayInputStream(DATA3.getBytes(StandardCharsets.UTF_8))) {
            doc = db.parse(is);
        }
        elem = (Element) doc.getDocumentElement();
        dataCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        dataCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
        dataCipher.doFinal(doc, elem, true);
        encrElem = (Element) elem.getFirstChild();
        assertEquals("EncryptedData", encrElem.getLocalName());
        assertNull(encrElem.getNextSibling());
        deCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        deCipher.init(XMLCipher.DECRYPT_MODE, secretKey);
        deCipher.doFinal(doc, encrElem);
        Node n = elem.getFirstChild();
        assertEquals(Node.COMMENT_NODE, n.getNodeType());
        n = n.getNextSibling();
        assertEquals(Node.PROCESSING_INSTRUCTION_NODE, n.getNodeType());
        n = n.getNextSibling();
        assertEquals(Node.ELEMENT_NODE, n.getNodeType());
        n = n.getNextSibling();
        assertEquals(Node.COMMENT_NODE, n.getNodeType());
        n = n.getNextSibling();
        assertEquals(Node.PROCESSING_INSTRUCTION_NODE, n.getNodeType());
        n = n.getNextSibling();
        assertNull(n);
    } else {
        LOG.warn("Test testPhysicalRepresentation skipped as " + "necessary algorithms not available");
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) XMLCipher(org.apache.xml.security.encryption.XMLCipher) Document(org.w3c.dom.Document) Attr(org.w3c.dom.Attr) SecretKey(javax.crypto.SecretKey) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) DESedeKeySpec(javax.crypto.spec.DESedeKeySpec) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 60 with XMLCipher

use of org.apache.xml.security.encryption.XMLCipher in project santuario-java by apache.

the class XMLCipherTest method testAES192Element3DESKWCipher.

/**
 * Test encryption using a generated AES 192 bit key that is
 * encrypted using a 3DES key.  Then reverse by decrypting
 * EncryptedKey by hand
 */
@org.junit.Test
public void testAES192Element3DESKWCipher() throws Exception {
    // source
    Document d = document();
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;
    String source = null;
    String target = null;
    if (haveISOPadding && haveKeyWraps) {
        source = toString(d);
        // Set up a Key Encryption Key
        byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
        DESedeKeySpec keySpec = new DESedeKeySpec(bits192);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        Key kek = keyFactory.generateSecret(keySpec);
        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(192);
        Key key = keygen.generateKey();
        cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES_KeyWrap);
        cipher.init(XMLCipher.WRAP_MODE, kek);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);
        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_192);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();
        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }
        builderKeyInfo.add(encryptedKey);
        ed = cipher.doFinal(d, e);
        // decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance();
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        EncryptedData encryptedData = cipher.loadEncryptedData(ed, ee);
        if (encryptedData == null) {
            System.out.println("ed is null");
        } else if (encryptedData.getKeyInfo() == null) {
            System.out.println("ki is null");
        }
        EncryptedKey ek = encryptedData.getKeyInfo().itemEncryptedKey(0);
        if (ek != null) {
            XMLCipher keyCipher = XMLCipher.getInstance();
            keyCipher.init(XMLCipher.UNWRAP_MODE, kek);
            key = keyCipher.decryptKey(ek, encryptedData.getEncryptionMethod().getAlgorithm());
        }
        // Create a new cipher just to be paranoid
        XMLCipher cipher3 = XMLCipher.getInstance();
        cipher3.init(XMLCipher.DECRYPT_MODE, key);
        dd = cipher3.doFinal(ed, ee);
        target = toString(dd);
        assertEquals(source, target);
    } else {
        LOG.warn("Test testAES192Element3DESKWCipher skipped as " + "necessary algorithms not available");
    }
}
Also used : EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) KeyInfo(org.apache.xml.security.keys.KeyInfo) Element(org.w3c.dom.Element) DESedeKeySpec(javax.crypto.spec.DESedeKeySpec) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyGenerator(javax.crypto.KeyGenerator) PublicKey(java.security.PublicKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Aggregations

XMLCipher (org.apache.xml.security.encryption.XMLCipher)74 Document (org.w3c.dom.Document)50 EncryptedKey (org.apache.xml.security.encryption.EncryptedKey)47 NodeList (org.w3c.dom.NodeList)44 SecretKey (javax.crypto.SecretKey)40 Element (org.w3c.dom.Element)33 DocumentBuilder (javax.xml.parsers.DocumentBuilder)30 InputStream (java.io.InputStream)29 KeyGenerator (javax.crypto.KeyGenerator)25 ArrayList (java.util.ArrayList)22 EncryptedData (org.apache.xml.security.encryption.EncryptedData)21 Key (java.security.Key)18 ByteArrayInputStream (java.io.ByteArrayInputStream)16 KeyInfo (org.apache.xml.security.keys.KeyInfo)16 PrivateKey (java.security.PrivateKey)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 DOMSource (javax.xml.transform.dom.DOMSource)13 XMLStreamReader (javax.xml.stream.XMLStreamReader)11 StreamResult (javax.xml.transform.stream.StreamResult)11 InboundXMLSec (org.apache.xml.security.stax.ext.InboundXMLSec)11