How to manage a 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 secretKey in a database for further decryption of the file. I am wondering how to store a SecretKey object in a database table. Should I serialize a key object? (secretKey serilaizable.) How to save a serialized object in a database? Which MYSQL data type should I use?

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

Any help would be greatly appreciated.

+5
source share
1 answer

There is a class in java - "Key Generator" - this class provides the functionality of a secret (symmetric) key generator.

Basically, you should use this class to generate a private key in one of the following ways:

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

This will create a secret key with a default length for the algorithm, which is passed as a parameter, in this example it will generate a 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 private keys to an array of characters, an array of bytes or a string, and then you can save them to any database using the following command:

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

or

 byte[] key = aesKey.getEncoded(); 

See the KeyGenerator class for more details: http://docs.oracle.com/javase/7/docs/api/javax/crypto/KeyGenerator.html

I am glad to help.

Thanks Ankit

+3
source

Source: https://habr.com/ru/post/1205844/


All Articles