Got it. The problem was that I had replaced

byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();

SecretKey key = new SecretKeySpec(keyBytes, "AES");


with


SecretKey key = keyFactory.generateSecret(keySpec);


This is not a problem for the generic version of the Bouncy Castle 
provider, but for some reason Android doesn't like it.


For completeness, I've included the final version below. Does it look OK?


Thanks again!


Matthew


KeyGenerator generator = KeyGenerator.getInstance("AES");

generator.init(128);

Key keyToBeWrapped = generator.generateKey();

Log.v("tag","input: " + new String(keyToBeWrapped.getEncoded()));

   

String password  = "password";

int iterationCount = 100;

int saltLength = 8; 

int keyLength = 256;


SecureRandom random = new SecureRandom();

byte[] salt = new byte[saltLength];

random.nextBytes(salt);

 

KeySpec keySpec = new PBEKeySpec(password.toCharArray(), 
salt, iterationCount, keyLength);

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(
"PBKDF2WithHmacSHA1");

 byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();

SecretKey key = new SecretKeySpec(keyBytes, "AES");

 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");

 

byte[] iv = new byte[cipher.getBlockSize()];

random.nextBytes(iv);

 

IvParameterSpec ivParams = new IvParameterSpec(iv);

   

cipher.init(Cipher.WRAP_MODE, key, ivParams);

byte[] wrappedKey = cipher.wrap(keyToBeWrapped);

Log.v("tag", "wrapped: " + new String(wrappedKey));


cipher.init(Cipher.UNWRAP_MODE, key, ivParams);

Key keyUnwrapped = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

Log.v("tag","unwrapped: " + new String(keyUnwrapped.getEncoded()));

-- 
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+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to