Search in sources :

Example 1 with XMLCipher

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

the class AMEncryptionProvider method decryptAndReplace.

/**
     * Decrypts an XML Document that contains encrypted data.
     * @param encryptedDoc XML Document with encrypted data.
     * @param privKey Key Encryption Key used for encryption.
     * @return org.w3c.dom.Document Decrypted XML Document.
     */
public Document decryptAndReplace(Document encryptedDoc, java.security.Key privKey) throws EncryptionException {
    EncryptionUtils.debug.message("************IN DECRYPT *************");
    if (encryptedDoc == null) {
        throw new EncryptionException(EncryptionUtils.bundle.getString("null encrypted doc"));
    }
    if (EncryptionUtils.debug.messageEnabled()) {
        EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: input encrypted DOC = " + XMLUtils.print(encryptedDoc));
    }
    Key encryptionKey = null;
    Document decryptedDoc = null;
    EncryptedKey encryptedKey = null;
    Element encryptedElementNext = null;
    XMLCipher cipher = null;
    NodeList nodes = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.ENC_XML_NS, "EncryptedData");
    int length = nodes.getLength();
    if (nodes == null || length == 0) {
        return encryptedDoc;
    }
    /**
         * Check for the encrypted key after the encrypted data.
         * if found, use that symmetric key for the decryption., otherwise
         * check if there's one in the encrypted data.
         */
    Element encryptedElem = (Element) encryptedDoc.getElementsByTagNameNS(EncryptionConstants.ENC_XML_NS, "EncryptedKey").item(0);
    try {
        cipher = XMLCipher.getInstance();
        cipher.init(XMLCipher.DECRYPT_MODE, null);
    } catch (Exception xe) {
        EncryptionUtils.debug.error("AMEncryptionProvider.decrypt" + "AndReplace: XML Decryption error for XMLCipher init :", xe);
        throw new EncryptionException(xe);
    }
    int i = 0;
    Element encryptedElement = (Element) nodes.item(i);
    while (i < length) {
        try {
            if (EncryptionUtils.debug.messageEnabled()) {
                EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: encrypted element (" + i + ") = " + XMLUtils.print(encryptedElement));
            }
            EncryptedData encryptedData = cipher.loadEncryptedData(encryptedDoc, encryptedElement);
            if (encryptedKey == null) {
                encryptedKey = cipher.loadEncryptedKey(encryptedDoc, encryptedElem);
                if (encryptedKey == null) {
                    encryptedKey = encryptedData.getKeyInfo().itemEncryptedKey(0);
                }
            }
            if (EncryptionUtils.debug.messageEnabled()) {
                EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: Encrypted key = " + toString(cipher.martial(encryptedDoc, encryptedKey)));
                EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: Encrypted Data (" + i + ") = " + toString(cipher.martial(encryptedDoc, encryptedData)));
            }
            if (encryptedKey != null) {
                XMLCipher keyCipher = XMLCipher.getInstance();
                if (privKey == null) {
                    privKey = getPrivateKey(encryptedKey.getKeyInfo());
                }
                keyCipher.init(XMLCipher.UNWRAP_MODE, privKey);
                encryptionKey = keyCipher.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
            }
            cipher = XMLCipher.getInstance();
            cipher.init(XMLCipher.DECRYPT_MODE, encryptionKey);
            i = i + 1;
            if (i < length) {
                encryptedElementNext = (Element) nodes.item(i);
            }
            decryptedDoc = cipher.doFinal(encryptedDoc, encryptedElement);
            encryptedElement = encryptedElementNext;
            if (EncryptionUtils.debug.messageEnabled()) {
                EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: decryptedDoc (" + (i - 1) + ") = " + XMLUtils.print(decryptedDoc));
            }
        } catch (Exception xe) {
            EncryptionUtils.debug.error("AMEncryptionProvider.decrypt" + "AndReplace: XML Decryption error.", xe);
            throw new EncryptionException(xe);
        }
    }
    if (EncryptionUtils.debug.messageEnabled()) {
        EncryptionUtils.debug.message("AMEncryptionProvider.decrypt" + "AndReplace: FINAL decryptedDoc = " + XMLUtils.print(decryptedDoc));
    }
    return decryptedDoc;
}
Also used : EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) 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) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 2 with XMLCipher

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

the class FMEncProvider method decrypt.

@Override
public Element decrypt(String xmlString, Set<PrivateKey> privateKeys) throws SAML2Exception {
    String classMethod = "FMEncProvider.decrypt: ";
    if (SAML2SDKUtils.debug.messageEnabled()) {
        SAML2SDKUtils.debug.message(classMethod + "Entering ...");
    }
    if (StringUtils.isEmpty(xmlString) || CollectionUtils.isEmpty(privateKeys)) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
    if (doc == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
    }
    Element rootElement = doc.getDocumentElement();
    if (rootElement == null) {
        SAML2SDKUtils.debug.error(classMethod + "Empty document.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("emptyDoc"));
    }
    Element firstChild = getNextElementNode(rootElement.getFirstChild());
    if (firstChild == null) {
        SAML2SDKUtils.debug.error(classMethod + "Missing the EncryptedData element.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingElementEncryptedData"));
    }
    Element secondChild = getNextElementNode(firstChild.getNextSibling());
    if (secondChild == null) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message(classMethod + "looking for encrytion key inside first child.");
        }
        NodeList nl = firstChild.getElementsByTagNameNS(SAML2Constants.NS_XMLENC, "EncryptedKey");
        if ((nl == null) || (nl.getLength() == 0)) {
            SAML2SDKUtils.debug.error(classMethod + "Missing the EncryptedKey element.");
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingElementEncryptedKey"));
        } else {
            // use the first EncryptedKey found
            secondChild = (Element) nl.item(0);
        }
    }
    XMLCipher cipher = null;
    try {
        cipher = XMLCipher.getInstance();
    } catch (XMLEncryptionException xe1) {
        SAML2SDKUtils.debug.error(classMethod + "Unable to get a cipher instance.", xe1);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("noCipher"));
    }
    try {
        cipher.init(XMLCipher.DECRYPT_MODE, null);
    } catch (XMLEncryptionException xe2) {
        SAML2SDKUtils.debug.error(classMethod + "Failed to initialize cipher for decryption mode", xe2);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedInitCipherForDecrypt"));
    }
    EncryptedData encryptedData = null;
    try {
        encryptedData = cipher.loadEncryptedData(doc, firstChild);
    } catch (XMLEncryptionException xe3) {
        SAML2SDKUtils.debug.error(classMethod + "Failed to load encrypted data", xe3);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedLoadingEncryptedData"));
    }
    EncryptedKey encryptedKey = null;
    try {
        encryptedKey = cipher.loadEncryptedKey(doc, secondChild);
    } catch (XMLEncryptionException xe4) {
        SAML2SDKUtils.debug.error(classMethod + "Failed to load encrypted key", xe4);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedLoadingEncryptedKey"));
    }
    Document decryptedDoc = null;
    if (encryptedKey != null && encryptedData != null) {
        XMLCipher keyCipher = null;
        try {
            keyCipher = XMLCipher.getInstance();
        } catch (XMLEncryptionException xe5) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to get a cipher instance " + "for decrypting secret key.", xe5);
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("noCipher"));
        }
        Key encryptionKey = getEncryptionKey(keyCipher, privateKeys, encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
        cipher = null;
        try {
            cipher = XMLCipher.getInstance();
        } catch (XMLEncryptionException xe8) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to get cipher instance for " + "final data decryption.", xe8);
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("noCipher"));
        }
        try {
            cipher.init(XMLCipher.DECRYPT_MODE, encryptionKey);
        } catch (XMLEncryptionException xe9) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to initialize cipher with secret key.", xe9);
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedInitCipherForDecrypt"));
        }
        try {
            decryptedDoc = cipher.doFinal(doc, firstChild);
        } catch (Exception e) {
            SAML2SDKUtils.debug.error(classMethod + "Failed to decrypt data.", e);
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedDecryptingData"));
        }
    }
    Element root = decryptedDoc.getDocumentElement();
    Element child = getNextElementNode(root.getFirstChild());
    if (child == null) {
        SAML2SDKUtils.debug.error(classMethod + "decrypted document contains empty element.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("failedDecryptingData"));
    }
    root.removeChild(child);
    decryptedDoc.replaceChild(child, root);
    return decryptedDoc.getDocumentElement();
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) XMLEncryptionException(org.apache.xml.security.encryption.XMLEncryptionException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) XMLEncryptionException(org.apache.xml.security.encryption.XMLEncryptionException)

Example 3 with XMLCipher

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

the class XMLSecurityDataFormat method encryptSymmetric.

private void encryptSymmetric(Exchange exchange, Document document, OutputStream stream) throws Exception {
    Key keyEncryptionKey;
    Key dataEncryptionKey;
    if (xmlCipherAlgorithm.equals(XMLCipher.TRIPLEDES)) {
        keyEncryptionKey = generateKeyEncryptionKey("DESede");
        dataEncryptionKey = generateDataEncryptionKey();
    } else if (xmlCipherAlgorithm.equals(XMLCipher.SEED_128)) {
        keyEncryptionKey = generateKeyEncryptionKey("SEED");
        dataEncryptionKey = generateDataEncryptionKey();
    } else if (xmlCipherAlgorithm.contains("camellia")) {
        keyEncryptionKey = generateKeyEncryptionKey("CAMELLIA");
        dataEncryptionKey = generateDataEncryptionKey();
    } else {
        keyEncryptionKey = generateKeyEncryptionKey("AES");
        dataEncryptionKey = generateDataEncryptionKey();
    }
    XMLCipher keyCipher = XMLCipher.getInstance(generateXmlCipherAlgorithmKeyWrap());
    keyCipher.init(XMLCipher.WRAP_MODE, keyEncryptionKey);
    encrypt(exchange, document, stream, dataEncryptionKey, keyCipher, keyEncryptionKey);
}
Also used : XMLCipher(org.apache.xml.security.encryption.XMLCipher) PublicKey(java.security.PublicKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey)

Example 4 with XMLCipher

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

the class EncryptedKeyResolver method engineLookupAndResolveSecretKey.

/**
 * {@inheritDoc}
 */
public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) {
    if (element == null) {
        return null;
    }
    LOG.debug("EncryptedKeyResolver - Can I resolve {}", element.getTagName());
    SecretKey key = null;
    boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element, EncryptionConstants._TAG_ENCRYPTEDKEY);
    if (isEncryptedKey) {
        LOG.debug("Passed an Encrypted Key");
        try {
            XMLCipher cipher = XMLCipher.getInstance();
            cipher.init(XMLCipher.UNWRAP_MODE, kek);
            if (internalKeyResolvers != null) {
                int size = internalKeyResolvers.size();
                for (int i = 0; i < size; i++) {
                    cipher.registerInternalKeyResolver(internalKeyResolvers.get(i));
                }
            }
            EncryptedKey ek = cipher.loadEncryptedKey(element);
            key = (SecretKey) cipher.decryptKey(ek, algorithm);
        } catch (XMLEncryptionException e) {
            LOG.debug(e.getMessage(), e);
        }
    }
    return key;
}
Also used : SecretKey(javax.crypto.SecretKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) XMLCipher(org.apache.xml.security.encryption.XMLCipher) XMLEncryptionException(org.apache.xml.security.encryption.XMLEncryptionException)

Example 5 with XMLCipher

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

the class KeyInfo method add.

/**
 * Method addEncryptedKey
 *
 * @param encryptedKey
 * @throws XMLEncryptionException
 */
public void add(EncryptedKey encryptedKey) throws XMLEncryptionException {
    if (encryptedKeys == null) {
        encryptedKeys = new ArrayList<>();
    }
    encryptedKeys.add(encryptedKey);
    XMLCipher cipher = XMLCipher.getInstance();
    appendSelf(cipher.martial(encryptedKey));
}
Also used : XMLCipher(org.apache.xml.security.encryption.XMLCipher)

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