Search in sources :

Example 1 with EncryptedData

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

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

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

the class XMLEncryption11Test method encryptDocument.

/**
 * Encrypt a Document using the given parameters.
 */
private Document encryptDocument(Document doc, EncryptedKey encryptedKey, Key sessionKey, String encryptionMethod) throws Exception {
    // Create the XMLCipher element
    XMLCipher cipher = XMLCipher.getInstance(encryptionMethod);
    cipher.init(XMLCipher.ENCRYPT_MODE, sessionKey);
    EncryptedData builder = cipher.getEncryptedData();
    KeyInfo builderKeyInfo = builder.getKeyInfo();
    if (builderKeyInfo == null) {
        builderKeyInfo = new KeyInfo(doc);
        builder.setKeyInfo(builderKeyInfo);
    }
    builderKeyInfo.add(encryptedKey);
    return cipher.doFinal(doc, doc.getDocumentElement());
}
Also used : KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData)

Example 4 with EncryptedData

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

the class XMLCipherTest method testAES256ElementRSAKWCipherUsingKEK.

/**
 * Test encryption using a generated AES 256 bit key that is
 * encrypted using an RSA key.  Reverse using KEK
 */
@org.junit.Test
public void testAES256ElementRSAKWCipherUsingKEK() 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) {
        source = toString(d);
        // Generate an RSA key
        KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = rsaKeygen.generateKeyPair();
        PrivateKey priv = kp.getPrivate();
        PublicKey pub = kp.getPublic();
        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        Key key = keygen.generateKey();
        cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
        cipher.init(XMLCipher.WRAP_MODE, pub);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);
        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_256);
        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);
        LOG.debug("Encrypted document");
        LOG.debug(toString(ed));
        // decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance(XMLCipher.AES_256);
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        cipher.setKEK(priv);
        dd = cipher.doFinal(ed, ee);
        target = toString(dd);
        assertEquals(source, target);
    } else {
        LOG.warn("Test testAES256ElementRSAKWCipherUsingKEK skipped as " + "necessary algorithms not available");
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) KeyInfo(org.apache.xml.security.keys.KeyInfo) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) KeyPairGenerator(java.security.KeyPairGenerator) EncryptedData(org.apache.xml.security.encryption.EncryptedData) 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 5 with EncryptedData

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

the class XMLCipherTest method testAES128ElementAES192KWCipherUsingKEK.

/**
 * Test encryption using a generated AES 128 bit key that is
 * encrypted using a AES 192 bit key.  Then reverse using the KEK
 */
@org.junit.Test
public void testAES128ElementAES192KWCipherUsingKEK() 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();
        Key kek = new SecretKeySpec(bits192, "AES");
        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(128);
        Key key = keygen.generateKey();
        cipher = XMLCipher.getInstance(XMLCipher.AES_192_KeyWrap);
        cipher.init(XMLCipher.WRAP_MODE, kek);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);
        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_128);
        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(XMLCipher.AES_128);
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        cipher.setKEK(kek);
        dd = cipher.doFinal(ed, ee);
        target = toString(dd);
        assertEquals(source, target);
    } else {
        LOG.warn("Test testAES128ElementAES192KWCipherUsingKEK skipped as " + "necessary algorithms not available");
    }
}
Also used : EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) KeyInfo(org.apache.xml.security.keys.KeyInfo) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Element(org.w3c.dom.Element) EncryptedData(org.apache.xml.security.encryption.EncryptedData) 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)

Aggregations

EncryptedData (org.apache.xml.security.encryption.EncryptedData)30 Element (org.w3c.dom.Element)26 EncryptedKey (org.apache.xml.security.encryption.EncryptedKey)24 XMLCipher (org.apache.xml.security.encryption.XMLCipher)21 Document (org.w3c.dom.Document)21 SecretKey (javax.crypto.SecretKey)20 KeyInfo (org.apache.xml.security.keys.KeyInfo)18 Key (java.security.Key)17 PrivateKey (java.security.PrivateKey)15 PublicKey (java.security.PublicKey)12 NodeList (org.w3c.dom.NodeList)10 SecretKeySpec (javax.crypto.spec.SecretKeySpec)7 XPath (javax.xml.xpath.XPath)5 XPathFactory (javax.xml.xpath.XPathFactory)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 KeyGenerator (javax.crypto.KeyGenerator)4 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)4 SecretKeyFactory (javax.crypto.SecretKeyFactory)3 DESedeKeySpec (javax.crypto.spec.DESedeKeySpec)3 DocumentBuilder (javax.xml.parsers.DocumentBuilder)3