Search in sources :

Example 41 with XMLCipher

use of org.apache.xml.security.encryption.XMLCipher 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 42 with XMLCipher

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

the class EncryptionUtils method decryptUsingDOM.

/**
 * Decrypt the document using the DOM API of Apache Santuario - XML Security for Java.
 */
public static void decryptUsingDOM(Document document, String algorithm, Key privateKey) throws Exception {
    XMLCipher cipher = XMLCipher.getInstance(algorithm);
    cipher.init(XMLCipher.DECRYPT_MODE, null);
    cipher.setKEK(privateKey);
    NodeList nodeList = document.getElementsByTagNameNS(XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(), XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart());
    for (int i = 0; i < nodeList.getLength(); i++) {
        Element ee = (Element) nodeList.item(i);
        cipher.doFinal(document, ee);
    }
}
Also used : NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) XMLCipher(org.apache.xml.security.encryption.XMLCipher)

Example 43 with XMLCipher

use of org.apache.xml.security.encryption.XMLCipher 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 44 with XMLCipher

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

the class AbstractPerformanceTest method doDOMEncryptionOutbound.

protected void doDOMEncryptionOutbound(File file, int tagCount) throws Exception {
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(file);
    XMLCipher cipher = XMLCipher.getInstance("http://www.w3.org/2001/04/xmlenc#aes256-cbc");
    cipher.init(XMLCipher.ENCRYPT_MODE, encryptionSymKey);
    document = cipher.doFinal(document, document.getDocumentElement());
    XMLUtils.outputDOM(document, new BufferedOutputStream(new FileOutputStream(new File(getTmpFilePath(), "encryption-dom-" + tagCount + ".xml"))));
}
Also used : DocumentBuilder(javax.xml.parsers.DocumentBuilder) XMLCipher(org.apache.xml.security.encryption.XMLCipher) Document(org.w3c.dom.Document)

Example 45 with XMLCipher

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

the class EncryptionCreationTest method decryptUsingDOM.

/**
 * Decrypt the document using DOM API and run some tests on the decrypted Document.
 */
private Document decryptUsingDOM(String algorithm, SecretKey secretKey, Key wrappingKey, Document document) throws Exception {
    XMLCipher cipher = XMLCipher.getInstance(algorithm);
    cipher.init(XMLCipher.DECRYPT_MODE, secretKey);
    if (wrappingKey != null) {
        cipher.setKEK(wrappingKey);
    }
    NodeList nodeList = document.getElementsByTagNameNS(XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(), XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart());
    Element ee = (Element) nodeList.item(0);
    return cipher.doFinal(document, ee);
}
Also used : NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) XMLCipher(org.apache.xml.security.encryption.XMLCipher)

Aggregations

XMLCipher (org.apache.xml.security.encryption.XMLCipher)79 Document (org.w3c.dom.Document)54 EncryptedKey (org.apache.xml.security.encryption.EncryptedKey)51 NodeList (org.w3c.dom.NodeList)48 SecretKey (javax.crypto.SecretKey)41 Element (org.w3c.dom.Element)37 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)22 Key (java.security.Key)19 ByteArrayInputStream (java.io.ByteArrayInputStream)16 KeyInfo (org.apache.xml.security.keys.KeyInfo)16 PrivateKey (java.security.PrivateKey)15 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 XMLEncryptionException (org.apache.xml.security.encryption.XMLEncryptionException)11