Search in sources :

Example 31 with EncryptedKey

use of org.apache.xml.security.encryption.EncryptedKey in project OpenAM by OpenRock.

the class AMEncryptionProvider method encryptAndReplace.

/**
     * Encrypts the given XML element in a given XML Context document.
     * @param doc the context XML Document.
     * @param element Element to be encrypted.
     * @param secretKeyAlg Encryption Key Algorithm.
     * @param keyStrength Encryption Key Strength.
     * @param kek Key Encryption Key.
     * @param kekStrength Key Encryption Key Strength,
     * @param providerID Provider ID
     * @param isEncryptResourceID A flag indicates whether it's to encrypt
     * 		ResourceID or not.
     * @return org.w3c.dom.Document EncryptedResourceID XML Document if
     * 		isEncryptResourceID is set. Otherwise, return the XML Document
     *		replaced with encrypted data for a given XML element.
     */
private org.w3c.dom.Document encryptAndReplace(org.w3c.dom.Document doc, org.w3c.dom.Element element, java.lang.String secretKeyAlg, int keyStrength, java.security.Key kek, int kekStrength, String providerID, boolean isEncryptResourceID) throws EncryptionException {
    if (doc == null || element == null || kek == null) {
        EncryptionUtils.debug.error("AMEncryptionProvider.encryptAnd" + "Replace: Null values");
        throw new EncryptionException(EncryptionUtils.bundle.getString("nullValues"));
    }
    SecretKey secretKey = null;
    String secretKeyAlgShortName = getEncryptionAlgorithmShortName(secretKeyAlg);
    if (providerID != null) {
        if (keyMap.containsKey(providerID)) {
            secretKey = (SecretKey) keyMap.get(providerID);
        } else {
            secretKey = generateSecretKey(secretKeyAlgShortName, keyStrength);
            keyMap.put(providerID, secretKey);
        }
    } else {
        secretKey = generateSecretKey(secretKeyAlgShortName, keyStrength);
    }
    if (secretKey == null) {
        throw new EncryptionException(EncryptionUtils.bundle.getString("generateKeyError"));
    }
    try {
        XMLCipher cipher = null;
        String keyEncAlg = kek.getAlgorithm();
        if (keyEncAlg.equals(EncryptionConstants.RSA)) {
            cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
        } else if (keyEncAlg.equals(EncryptionConstants.TRIPLEDES)) {
            cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES_KeyWrap);
        } else if (keyEncAlg.equals(EncryptionConstants.AES)) {
            if (kekStrength == 0 || kekStrength == 128) {
                cipher = XMLCipher.getInstance(XMLCipher.AES_128_KeyWrap);
            } else if (kekStrength == 192) {
                cipher = XMLCipher.getInstance(XMLCipher.AES_192_KeyWrap);
            } else if (kekStrength == 256) {
                cipher = XMLCipher.getInstance(XMLCipher.AES_256_KeyWrap);
            } else {
                throw new EncryptionException(EncryptionUtils.bundle.getString("invalidKeyStrength"));
            }
        } else {
            throw new EncryptionException(EncryptionUtils.bundle.getString("unsupportedKeyAlg"));
        }
        // Encrypt the key with key encryption key
        cipher.init(XMLCipher.WRAP_MODE, kek);
        EncryptedKey encryptedKey = cipher.encryptKey(doc, secretKey);
        KeyInfo insideKi = new KeyInfo(doc);
        X509Data x509Data = new X509Data(doc);
        x509Data.addCertificate((X509Certificate) keyProvider.getCertificate((PublicKey) kek));
        insideKi.add(x509Data);
        encryptedKey.setKeyInfo(insideKi);
        String ekID = null;
        if (isEncryptResourceID) {
            ekID = com.sun.identity.saml.common.SAMLUtils.generateID();
            encryptedKey.setId(ekID);
        }
        if (EncryptionUtils.debug.messageEnabled()) {
            EncryptionUtils.debug.message("AMEncryptionProvider.encrypt" + "AndReplace: Encrypted key = " + toString(cipher.martial(doc, encryptedKey)));
        }
        String encAlgorithm = getEncryptionAlgorithm(secretKeyAlgShortName, keyStrength);
        cipher = XMLCipher.getInstance(encAlgorithm);
        cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
        EncryptedData builder = cipher.getEncryptedData();
        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(doc);
            builder.setKeyInfo(builderKeyInfo);
        }
        if (isEncryptResourceID) {
            builderKeyInfo.addKeyName(providerID);
            builderKeyInfo.addRetrievalMethod("#" + ekID, null, "http://www.w3.org/2001/04/xmlenc#EncryptedKey");
        } else {
            builderKeyInfo.add(encryptedKey);
        }
        Document result = cipher.doFinal(doc, element);
        if (isEncryptResourceID) {
            Element ee = (Element) result.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData").item(0);
            Node parentNode = ee.getParentNode();
            Element newone = result.createElementNS("urn:liberty:disco:2003-08", "EncryptedResourceID");
            parentNode.replaceChild(newone, ee);
            newone.appendChild(ee);
            Element ek = cipher.martial(doc, encryptedKey);
            Element carriedName = doc.createElementNS("http://www.w3.org/2001/04/xmlenc#", "xenc:CarriedKeyName");
            carriedName.appendChild(doc.createTextNode(providerID));
            ek.appendChild(carriedName);
            newone.appendChild(ek);
        }
        return result;
    } catch (Exception xe) {
        EncryptionUtils.debug.error("AMEncryptionProvider.encryptAnd" + "Replace: XML Encryption error", xe);
        throw new EncryptionException(xe);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) KeyInfo(org.apache.xml.security.keys.KeyInfo) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 32 with EncryptedKey

use of org.apache.xml.security.encryption.EncryptedKey in project testcases by coheigea.

the class EncryptionUtils method encryptUsingDOM.

/**
 * Encrypt the document using the DOM API of Apache Santuario - XML Security for Java.
 * It encrypts a list of QNames that it finds in the Document via XPath. If a wrappingKey
 * is supplied, this is used to encrypt the encryptingKey + place it in an EncryptedKey
 * structure.
 */
public static void encryptUsingDOM(Document document, List<QName> namesToEncrypt, String algorithm, Key encryptingKey, String keyTransportAlgorithm, PublicKey wrappingKey, boolean content) throws Exception {
    XMLCipher cipher = XMLCipher.getInstance(algorithm);
    cipher.init(XMLCipher.ENCRYPT_MODE, encryptingKey);
    if (wrappingKey != null) {
        XMLCipher newCipher = XMLCipher.getInstance(keyTransportAlgorithm);
        newCipher.init(XMLCipher.WRAP_MODE, wrappingKey);
        EncryptedKey encryptedKey = newCipher.encryptKey(document, encryptingKey);
        // Create a KeyInfo for the EncryptedKey
        KeyInfo encryptedKeyKeyInfo = encryptedKey.getKeyInfo();
        if (encryptedKeyKeyInfo == null) {
            encryptedKeyKeyInfo = new KeyInfo(document);
            encryptedKeyKeyInfo.getElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dsig", "http://www.w3.org/2000/09/xmldsig#");
            encryptedKey.setKeyInfo(encryptedKeyKeyInfo);
        }
        encryptedKeyKeyInfo.add(wrappingKey);
        // Create a KeyInfo for the EncryptedData
        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 (QName nameToEncrypt : namesToEncrypt) {
        String expression = "//*[local-name()='" + nameToEncrypt.getLocalPart() + "']";
        NodeList elementsToEncrypt = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
        for (int i = 0; i < elementsToEncrypt.getLength(); i++) {
            Element elementToEncrypt = (Element) elementsToEncrypt.item(i);
            Assert.assertNotNull(elementToEncrypt);
            document = cipher.doFinal(document, elementToEncrypt, content);
        }
    }
    String expression = "//xenc:EncryptedData[1]";
    Element encElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
    Assert.assertNotNull(encElement);
}
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) QName(javax.xml.namespace.QName) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData)

Example 33 with EncryptedKey

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

the class KeyWrapEncryptionCreationTest method decryptUsingDOM.

private Document decryptUsingDOM(Document document, Key keyWrappingKey) throws Exception {
    NodeList nodeList = document.getElementsByTagNameNS(XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(), XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart());
    Element ee = (Element) nodeList.item(0);
    // Need to pre-load the Encrypted Data so we can get the key info
    XMLCipher cipher = XMLCipher.getInstance();
    cipher.init(XMLCipher.DECRYPT_MODE, null);
    EncryptedData encryptedData = cipher.loadEncryptedData(document, ee);
    XMLCipher kwCipher = XMLCipher.getInstance();
    kwCipher.init(XMLCipher.UNWRAP_MODE, keyWrappingKey);
    KeyInfo ki = encryptedData.getKeyInfo();
    EncryptedKey encryptedKey = ki.itemEncryptedKey(0);
    Key symmetricKey = kwCipher.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
    cipher.init(XMLCipher.DECRYPT_MODE, symmetricKey);
    return cipher.doFinal(document, ee);
}
Also used : KeyInfo(org.apache.xml.security.keys.KeyInfo) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) SecretKey(javax.crypto.SecretKey)

Example 34 with EncryptedKey

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

the class KeyWrapEncryptionVerificationTest method testAES192KW.

@Test
public void testAES192KW() 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
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(192);
    SecretKey key = keygen.generateKey();
    // Set up the Key Wrapping Key
    XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_192_KeyWrap);
    keygen = KeyGenerator.getInstance("AES");
    keygen.init(192);
    SecretKey keyWrappingKey = keygen.generateKey();
    cipher.init(XMLCipher.WRAP_MODE, keyWrappingKey);
    EncryptedKey encryptedKey = cipher.encryptKey(document, key);
    // Encrypt using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    String encryptionAlgorithm = XMLCipher.AES_192;
    encrypt(encryptedKey, encryptionAlgorithm, document, localNames, key);
    // Check the CreditCard encrypted ok
    NodeList nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
    Assert.assertEquals(nodeList.getLength(), 0);
    // XMLUtils.outputDOM(document, System.out);
    // 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));
    final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
    // Decrypt
    XMLSecurityProperties properties = new XMLSecurityProperties();
    properties.setDecryptionKey(keyWrappingKey);
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
    document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
    // Check the CreditCard decrypted ok
    nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
    Assert.assertEquals(nodeList.getLength(), 1);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) StreamResult(javax.xml.transform.stream.StreamResult) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InboundXMLSec(org.apache.xml.security.stax.ext.InboundXMLSec) Document(org.w3c.dom.Document) SecretKey(javax.crypto.SecretKey) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLSecurityProperties(org.apache.xml.security.stax.ext.XMLSecurityProperties) TestSecurityEventListener(org.apache.xml.security.test.stax.signature.TestSecurityEventListener) KeyGenerator(javax.crypto.KeyGenerator) Test(org.junit.Test)

Example 35 with EncryptedKey

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

the class KeyWrapEncryptionVerificationTest method testAES128KW.

@Test
public void testAES128KW() 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
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);
    SecretKey key = keygen.generateKey();
    // Set up the Key Wrapping Key
    XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_128_KeyWrap);
    keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);
    SecretKey keyWrappingKey = keygen.generateKey();
    cipher.init(XMLCipher.WRAP_MODE, keyWrappingKey);
    EncryptedKey encryptedKey = cipher.encryptKey(document, key);
    // Encrypt using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    String encryptionAlgorithm = XMLCipher.AES_128;
    encrypt(encryptedKey, encryptionAlgorithm, document, localNames, key);
    // Check the CreditCard encrypted ok
    NodeList nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
    Assert.assertEquals(nodeList.getLength(), 0);
    // XMLUtils.outputDOM(document, System.out);
    // 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));
    final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
    // Decrypt
    XMLSecurityProperties properties = new XMLSecurityProperties();
    properties.setDecryptionKey(keyWrappingKey);
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
    document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
    // Check the CreditCard decrypted ok
    nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
    Assert.assertEquals(nodeList.getLength(), 1);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) StreamResult(javax.xml.transform.stream.StreamResult) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InboundXMLSec(org.apache.xml.security.stax.ext.InboundXMLSec) Document(org.w3c.dom.Document) SecretKey(javax.crypto.SecretKey) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLSecurityProperties(org.apache.xml.security.stax.ext.XMLSecurityProperties) TestSecurityEventListener(org.apache.xml.security.test.stax.signature.TestSecurityEventListener) KeyGenerator(javax.crypto.KeyGenerator) Test(org.junit.Test)

Aggregations

EncryptedKey (org.apache.xml.security.encryption.EncryptedKey)54 XMLCipher (org.apache.xml.security.encryption.XMLCipher)44 Document (org.w3c.dom.Document)43 SecretKey (javax.crypto.SecretKey)38 NodeList (org.w3c.dom.NodeList)35 DocumentBuilder (javax.xml.parsers.DocumentBuilder)28 KeyGenerator (javax.crypto.KeyGenerator)27 InputStream (java.io.InputStream)23 ArrayList (java.util.ArrayList)23 Key (java.security.Key)21 Element (org.w3c.dom.Element)20 EncryptedData (org.apache.xml.security.encryption.EncryptedData)18 PrivateKey (java.security.PrivateKey)16 KeyInfo (org.apache.xml.security.keys.KeyInfo)16 ByteArrayInputStream (java.io.ByteArrayInputStream)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 XMLStreamReader (javax.xml.stream.XMLStreamReader)12 DOMSource (javax.xml.transform.dom.DOMSource)12 StreamResult (javax.xml.transform.stream.StreamResult)12 InboundXMLSec (org.apache.xml.security.stax.ext.InboundXMLSec)12