6

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.

Lokesh Kumar
  • 801
  • 2
  • 8
  • 13
  • 1
    you need to use `blob` for storing objects and object must be serialized before storing in DB. See this for more information. http://stackoverflow.com/questions/2747203/want-to-store-object-in-mysql-database – smali Oct 30 '14 at 08:45
  • what will be datatype of secret key – Lokesh Kumar Oct 30 '14 at 08:53
  • Use String Object for storing secret key. – smali Oct 30 '14 at 08:58
  • please send me code for update secret key in mysql database and how to use it – Lokesh Kumar Oct 30 '14 at 09:06
  • You're probably doing this wrong. If this is long-term storage you probably should be using PKI rather than symmetric encryption. – user207421 Oct 30 '14 at 09:13
  • Hi EJP I want to use symmetric encryption algo for encryption and decryption in different times so in both time how can i hold the secret key? – Lokesh Kumar Oct 30 '14 at 10:14

1 Answers1

9

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.

Bhanu
  • 663
  • 5
  • 13
  • Hi Lokesh, if answer is useful then use upwards arrow to vote it up, otherwise if your problem is not yet solve, then let me know the issue. – Bhanu Nov 03 '14 at 15:48