Search code examples
javabouncycastleencryptionencryption-symmetric

Wrapping and unwrapping encryption key fails (javax.crypto)


I have the following test code to encrypt and decrypt a string. It works fine if I leave out the wrapping and unwrapping code for my key in test(), but when I try to wrap my key, and then unwrap it again and use it for the decryption, it fails and I don't get "Test" back as the resulting decrypted string but "�J��" instead.

Does anybody see the error I'm doing with the wrapping and unwrapping? Thanks.

private static void test() throws Exception {

    // create wrap key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AESWrap");
    keyGenerator.init(256);
    Key wrapKey = keyGenerator.generateKey();

    SecretKey key = generateKey(PASSPHRASE);
    Cipher cipher;

    // wrap key
    cipher = Cipher.getInstance("AESWrap");
    cipher.init(Cipher.WRAP_MODE, wrapKey);
    byte[] wrappedKeyBytes = cipher.wrap(key);

    // unwrap key again
    cipher.init(Cipher.UNWRAP_MODE, wrapKey);
    key = (SecretKey)cipher.unwrap( wrappedKeyBytes, "AES/CTR/NOPADDING", Cipher.SECRET_KEY);

    // encrypt
    cipher = Cipher.getInstance("AES/CTR/NOPADDING");
    cipher.init(Cipher.ENCRYPT_MODE, key, generateIV(cipher), random);
    byte[] b = cipher.doFinal("Test".toString().getBytes());

    // decrypt
    cipher = Cipher.getInstance("AES/CTR/NOPADDING");
    cipher.init(Cipher.DECRYPT_MODE, key, generateIV(cipher), random);
    b = cipher.doFinal(b);

    System.out.println(new String(b));  
    // should output "Test", but outputs �J�� if wrapping/unwrapping

}

And the two helper methods that are called in the code above:

private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
    byte [] ivBytes = new byte[cipher.getBlockSize()];
    random.nextBytes(ivBytes);    // random = new SecureRandom();
    return new IvParameterSpec(ivBytes);
}

private static SecretKey generateKey(String passphrase) throws Exception {
    PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALGORITHM); //"PBEWITHSHA256AND256BITAES-CBC-BC"
    return keyFactory.generateSecret(keySpec);
}

Solution

  • It looks like you're giving a different IV to cipher.init(Cipher.ENCRYPT_MODE, ...) and cipher.init(Cipher.DECRYPT_MODE, ...) by calling generateIV() twice.