How to manage secret Key in java
Asked Answered
F

1

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.

Fraase answered 30/10, 2014 at 8:41 Comment(6)
you need to use blob for storing objects and object must be serialized before storing in DB. See this for more information. #2747703Confederacy
what will be datatype of secret keyFraase
Use String Object for storing secret key.Confederacy
please send me code for update secret key in mysql database and how to use itFraase
You're probably doing this wrong. If this is long-term storage you probably should be using PKI rather than symmetric encryption.Moise
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?Fraase
H
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.

Holms answered 30/10, 2014 at 15:13 Comment(1)
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.Holms

© 2022 - 2024 — McMap. All rights reserved.