in src/main/java/org/apache/xml/security/encryption/XMLCipher.java [1459:1543]
public Key decryptKey(EncryptedKey encryptedKey, String algorithm)
throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Decrypting key from previously loaded EncryptedKey...");
if (cipherMode != UNWRAP_MODE) {
throw new XMLEncryptionException("empty", "XMLCipher unexpectedly not in UNWRAP_MODE...");
}
if (algorithm == null) {
throw new XMLEncryptionException("empty", "Cannot decrypt a key without knowing the algorithm");
}
if (key == null) {
LOG.log(Level.DEBUG, "Trying to find a KEK via key resolvers");
KeyInfo ki = encryptedKey.getKeyInfo();
if (ki != null) {
ki.setSecureValidation(secureValidation);
try {
String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm();
String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg);
if ( "RSA".equals(keyType) || "EC".equals(keyType)) {
key = ki.getPrivateKey();
} else {
key = ki.getSecretKey();
}
}
catch (Exception e) {
LOG.log(Level.DEBUG, e.getMessage(), e);
}
}
if (key == null) {
LOG.log(Level.ERROR, "XMLCipher::decryptKey unable to resolve a KEK");
throw new XMLEncryptionException("empty", "Unable to decrypt without a KEK");
}
}
// Obtain the encrypted octets
XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey);
cipherInput.setSecureValidation(secureValidation);
byte[] encryptedBytes = cipherInput.getBytes();
String jceKeyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(algorithm);
LOG.log(Level.DEBUG, "JCE Key Algorithm: {0}", jceKeyAlgorithm);
Cipher c;
if (contextCipher == null) {
// Now create the working cipher
c =
constructCipher(
encryptedKey.getEncryptionMethod().getAlgorithm(),
encryptedKey.getEncryptionMethod().getDigestAlgorithm()
);
} else {
c = contextCipher;
}
Key ret;
AlgorithmParameterSpec params;
try {
params = getAlgorithmParameters(encryptedKey);
} catch (XMLSecurityException e) {
throw new XMLEncryptionException(e);
}
try {
if (params == null) {
c.init(Cipher.UNWRAP_MODE, key);
} else if (params instanceof OAEPParameterSpec) {
c.init(Cipher.UNWRAP_MODE, key, params);
}
if (params instanceof KeyAgreementParameters) {
Key wrapKey = KeyUtils.aesWrapKeyWithDHGeneratedKey((KeyAgreementParameters) params);
c.init(Cipher.UNWRAP_MODE, wrapKey);
}
ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY);
} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
throw new XMLEncryptionException(e);
}
LOG.log(Level.DEBUG, "Decryption of key type {0} OK", algorithm);
return ret;
}