Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to store/restore encryption key for decrypting string in java

For encryption I use something like this:

SecretKey aesKey = KeyGenerator.getInstance("AES").generateKey();
StringEncrypter aesEncrypt = new StringEncrypter(aesKey, aesKey.getAlgorithm());
String aesEncrypted= aesEncrypt.encrypt(StringContent);

If I print out aesKey I get: "javax.crypto.spec.SecretKeySpec@1708d".

So for encryption I would like to ask user for key but dont know how and what format should it be. My plan was something like this:

SecretKey aesKey = javax.crypto.spec.SecretKeySpec@1708d;
StringEncrypter aesEncrypt = new StringEncrypter(aesKey, aesKey.getAlgorithm());
String aesDecrypt = aesEncrypt.decrypt(aesEncrypted);

But seems its not working. Is there some easy way to print out the key after encryption to console so user can save it(or remember it) and then Use for Decryption ?

Whole code is here:Cannot decrypt cyphertext from text file, symmetric key implement. in java So Im sorry for posting again but Im not sure If the code is even readable(I'm newbie).

like image 737
dave91 Avatar asked Dec 17 '09 22:12

dave91


People also ask

Which algorithm is best for encryption and decryption in Java?

The Advanced Encryption Standard (AES, Rijndael) is a block cipher encryption and decryption algorithm, the most used encryption algorithm in the worldwide. The AES processes block of 128 bits using a secret key of 128, 192, or 256 bits.


1 Answers

I've had to do this myself recently. And while the other answers here led me in the right direction, it could have been easier. So here is my "share" for the day, a couple of helper methods for simple AES key manipulation. (Note the dependency on Apache Commons and Codec.)

This is all in a git repo now: github.com/stuinzuri/SimpleJavaKeyStore

import static org.apache.commons.codec.binary.Hex.*;
import static org.apache.commons.io.FileUtils.*;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import org.apache.commons.codec.DecoderException;

public static SecretKey generateKey() throws NoSuchAlgorithmException
{
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(256); // 128 default; 192 and 256 also possible
    return keyGenerator.generateKey();
}

public static void saveKey(SecretKey key, File file) throws IOException
{
    char[] hex = encodeHex(key.getEncoded());
    writeStringToFile(file, String.valueOf(hex));
}

public static SecretKey loadKey(File file) throws IOException
{
    String data = new String(readFileToByteArray(file));
    byte[] encoded;
    try {
        encoded = decodeHex(data.toCharArray());
    } catch (DecoderException e) {
        e.printStackTrace();
        return null;
    }
    return new SecretKeySpec(encoded, "AES");
}
like image 136
Stu Thompson Avatar answered Oct 13 '22 17:10

Stu Thompson