Ok.  I think I see your problem:

String algorithm = encryptedKey.getEncryptionMethod().getAlgorithm();

Key secretKey = xmlCipherKey.decryptKey(encryptedKey,algorithm );

The algorithm URI that you pass into the XMLCipher#decryptKey method is the algorithm URI for the wrapped key that you are decrypting, *not* the one associated with the key encryption key itself. When it gets unwrapped/decrypted, it's just an array of bytes. You have to give it structure by telling it how to interpret that byte[] so it can produce a specific SecretKey impl (AES, triple DES, etc).

So in your case it would be the AES one for the data encryption key. So, you would pull that from the EncryptedData/EncryptionMethod/@Algorithm attribute, not the EncryptedKey attribute.

--Brent


sermagico wrote:
Hi Brent,
thank you for your reply, I made a mistake in explanation, in fact I already
use the public key for wrapping and the private key for unwrapping (in the
code private key is pkey).
Sorry for the misunderstanding. I hope you can give me a hand.
Thank you in advance.
Sergio.


Brent Putman wrote:
You have it backwards. You should encrypt/wrap the AES data encryption key with the recipient's *public* key. The recipient then decrypts with their *private* key.

If you think about the use cases, you'll quickly realize why that is.

--Brent


sermagico wrote:
Hi all,
I try to develop an application for xml encryption/decryption, but I have
some issue. I encrypt a file with a AES key, then I wrap this key with a
RSAprivateKey and I store it (wrapped AES) in the same xml file. Unfortunately when I try to unwrap the AES key with the PublicKey
associated
with the previous PrivateKey the below exception is raised up:

Exception in thread "main"
org.apache.xml.security.encryption.XMLEncryptionException: unknown key
type
passed to RSA
Original Exception was java.security.InvalidKeyException: unknown key
type
passed to RSA


PublicKey and PrivateKey are stored on a smartcard.
This is my code:

        XMLCipher CKey= XMLCipher.getInstance();
        XMLCipher CMsg= XMLCipher.getInstance();
        CKey.init(XMLCipher.UNWRAP_MODE, this.pkey);
        CMsg.init(XMLCipher.DECRYPT_MODE, null);
Element encryptedDataElement = (Element) document .getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS,
                EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);
EncryptedData encryptedData =
xmlCipherMsg.loadEncryptedData(document,
                encryptedDataElement);
        EncryptedKey encryptedKey = encryptedData.getKeyInfo()
        .itemEncryptedKey(0);
String algorithm =
encryptedKey.getEncryptionMethod().getAlgorithm();
CipherValue Value =
encryptedKey.getCipherData().getCipherValue();
//Exception here
        Key secretKey = xmlCipherKey.decryptKey(encryptedKey,algorithm );
I hope you can help me.
Thank you in advance.
Best regards.

Sergio.

Reply via email to