Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage secret Key in java

I am developing a Java cryptography application. I want to encrypt a file using symmetric algorithms such as AES or DES and store the secretKey in a database for future decryption of the file. I am wondering how to store the SecretKey object in a database table. Should I serialize the key object? (secretKey is serilaizable.) How to store serialized object in database? what MYSQL data type should I use?

Another solution is to get the raw byte[] of key, convert it to base64 and store in database. I can later on decode the base64 key to the original Raw key, but the problem is in converting the raw key to SecretKey object.

Any help would be highly appreciated.

like image 799
Lokesh Kumar Avatar asked Oct 30 '14 08:10

Lokesh Kumar


1 Answers

There is a class in java - 'Key Generator' - This class provides the functionality of secret (symmetric) keys generator.

You basically need to use this class for secret key generation, in one of following manner :

SecretKey  aesKey  = KeyGenerator.getInstance("AES").generateKey();

This will generated secret key with default length for the algorithm which is passed as parameter, in this example it will generate secret key for 128 bits (default for AES).

Or use the following function :

public static SecretKey generateSecretKey()
{  
   KeyGenerator keyGener  = KeyGenerator.getInstance("AES");
   keyGener.init(256)   // here you can pass any valid length
   return keyGener.generateKey();
}

You can convert these generated secret keys to character array, byte array or string and then these can be stored with any database, use following :

char[] key  = encodeHex(aesKey.getEncoded());

or

byte[] key = aesKey.getEncoded();

For more detail see the KeyGenerator class : http://docs.oracle.com/javase/7/docs/api/javax/crypto/KeyGenerator.html

Happy to help.

like image 151
Bhanu Avatar answered Oct 05 '22 22:10

Bhanu