Element encryptedDataDOM, Crypto sigCrypto, CallbackHandler callbackHandler
) throws WSSecurityException {
Element encKeyElement = getNode(encryptedDataDOM, WSConstants.ENC_NS, "EncryptedKey", 0);
if (encKeyElement == null) {
LOG.log(Level.FINE, "EncryptedKey element is not available");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
X509Certificate cert = loadCertificate(sigCrypto, encKeyElement);
if (cert == null) {
LOG.fine("X509Certificate cannot be retrieved from EncryptedKey element");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
// now start decrypting
String keyEncAlgo = getEncodingMethodAlgorithm(encKeyElement);
String digestAlgo = getDigestMethodAlgorithm(encKeyElement);
Element cipherValue = getNode(encKeyElement, WSConstants.ENC_NS, "CipherValue", 0);
if (cipherValue == null) {
LOG.fine("CipherValue element is not available");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
if (callbackHandler == null) {
LOG.fine("A CallbackHandler must be configured to decrypt encrypted Assertions");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
PrivateKey key = null;
try {
key = sigCrypto.getPrivateKey(cert, callbackHandler);
} catch (Exception ex) {
LOG.log(Level.FINE, "Encrypted key can not be decrypted", ex);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
Cipher cipher =
EncryptionUtils.initCipherWithKey(keyEncAlgo, digestAlgo, Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = null;
try {
byte[] encryptedBytes = Base64Utility.decode(cipherValue.getTextContent().trim());
decryptedBytes = cipher.doFinal(encryptedBytes);
} catch (Base64Exception ex) {
LOG.log(Level.FINE, "Base64 decoding has failed", ex);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
} catch (Exception ex) {
LOG.log(Level.FINE, "Encrypted key can not be decrypted", ex);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
String symKeyAlgo = getEncodingMethodAlgorithm(encryptedDataDOM);
byte[] decryptedPayload = null;
try {
decryptedPayload = decryptPayload(encryptedDataDOM, decryptedBytes, symKeyAlgo);
} catch (Exception ex) {
LOG.log(Level.FINE, "Payload can not be decrypted", ex);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
Document payloadDoc = null;
try {
payloadDoc = StaxUtils.read(new InputStreamReader(new ByteArrayInputStream(decryptedPayload),
"UTF-8"));
return payloadDoc.getDocumentElement();
} catch (Exception ex) {
LOG.log(Level.FINE, "Payload document can not be created", ex);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
}