Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Contributor
Posts: 14
Registered: ‎04-23-2012
My Device: Bold
My Carrier: 2063103963

Example for deriving a key using PBKDF2

Howdy;

 

Can anyone provide me with an example of using the BB APIs to derive a key from a password and a salt using PBKDF2 (i.e. RFC2898) with SHA1 or SHA256 as the PRF.  I'm sure this functionality is somewhere in the SDK but I can't seem to find it.  

 

Thanks very much.

 

ShaunB...

Highlighted
Contributor
Posts: 14
Registered: ‎04-23-2012
My Device: Bold
My Carrier: 2063103963

Re: Example for deriving a key using PBKDF2

I managed to figure it out. For anyone else who needs this - using SHA-1 - the following will do the trick:


public byte[] deriveUsingPBKDF2(byte[] key,
                                byte[] salt,
                                int iterations,
                                int resultSize)
{
   byte[] result = null;

 

   try
   {
      PKCS5KDF2PseudoRandomSource kdf =
                  new PKCS5KDF2PseudoRandomSource(key, salt, iterations);
      result = kdf.getBytes(resultSize);
   }
   catch( Exception e )
   {
      System.out.println("deriveUsingPBKDF2 exception: " + e.toString());
      result = null;
   }

 

   return result;
}

 

ShaunB...

New Contributor
Posts: 2
Registered: ‎05-03-2011
My Device: Torch
My Carrier: Docomo

Re: Example for deriving a key using PBKDF2

Hello Shaun,

 

I wanted to encrypt my data using PBKDF2 With Hmac SHA1. PBKDF2 encryption you explained but still im not able to generate the required key. can you help me in that.

Please find the equivalent java code below:

 

byte[] saltBytes = new byte[1024];
SecureRandom rnd = new SecureRandom();

/**
* Generate random salt
*/
rnd.nextBytes(saltBytes);


factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");


KeySpec spec = new PBEKeySpec(charArray, saltBytes, NUMBER_OF_ITERATIONS, KEY_SIZE_TO_USE);
secretKey = factory.generateSecret(spec);
Please help me out.
Thanks!