Sunday, December 16, 2012

Re: [android-developers] Cipher.wrap() not working in Android 4.2?

On Sat, Dec 15, 2012 at 12:17 PM, Matthew Fleming <mgflem@gmail.com> wrote:
>>
>> You can also try deriving the wrap key separately with something like:
>>
>> KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt,
>> ITERATION_COUNT, KEY_LENGTH);
>> SecretKeyFactory keyFactory = SecretKeyFactory
>> .getInstance("PBKDF2WithHmacSHA1");
>> SecretKey key = keyFactory.generateSecret(keySpec);
>>
>> And initialize the Cipher in WRAP mode with this SecretKey.
>
>
> Good thought, but it also does not work. The problem is the same:
> java.lang.UnsupportedOperationException, when I try to wrap the key. This
> only happens in Android 4.2. Everything works fine in 4.1 and every other
> previous version I've tested.
>

You might want to show some code, stack traces and more details.
The code below seems to work fine (utility method omitted for brevity).
What keys are you trying to wrap, and with what algorithm(s)?

This wraps a key with itself which is not very useful, but makes for a
shorter sample. And unless you are doing something special or using a
hardware module (HSM), wrapping is generally not really different from
encryption (just does a few checks to make sure what you get is a
valid-looking key), so you can also use ENCRYPT_MODE, if that
works for you .

byte[] salt = generateSalt();
byte[] iv = generateIv(128 / 8);
IvParameterSpec ivParams = new IvParameterSpec(iv);
SecretKey key = deriveKeyPbkdf2(salt, "password");
Log.d(TAG, "Key bytes: " + Crypto.toHex(key.getEncoded()));

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.WRAP_MODE, key, ivParams);
byte[] wrapped = c.wrap(key);
Log.d(TAG, "wrapped: " + toHex(wrapped));

c.init(Cipher.UNWRAP_MODE, key, ivParams);
SecretKey unwrapped = (SecretKey) c.unwrap(wrapped, "AES",
Cipher.SECRET_KEY);
Log.d(TAG, "unwrapped: " + toHex(unwrapped.getEncoded()));

Output (you might get different output if using random salt and IV (as
you should):

D/MainActivity(17692): Key bytes:
52EC700A0B0460DC957FBE2A4A19D816055C025E1D47A9826E6B55F19334AAD0
D/MainActivity(17692): wrapped:
A80332EEC9F0808B1965879AAFA0BE08276FDA865E3EDF80D21AAA23F90E7E229241389A72466C9703A5B74C70D52747
D/MainActivity(17692): unwrapped:
52EC700A0B0460DC957FBE2A4A19D816055C025E1D47A9826E6B55F19334AAD0

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment