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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With