Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Key from string?

I need to generate a Key from a string, such that I can always create the same key from the same string. (Specifically a Key object, so that I can use it to create a Cipher in turn to create a SealedObject)

Is this possible in Java, and what class/method combination should I be looking at to do so?

like image 836
Jon Story Avatar asked Mar 02 '12 16:03

Jon Story


People also ask

How do you generate a secret key from a string?

We can use the SecretKeyFactory class with the PBKDF2WithHmacSHA256 algorithm for generating a key from a given password.

How do you generate a random 256 bit session key in Java?

KeyGenerator keyGen = KeyGenerator. getInstance("AES"); keyGen. init(256); // for example SecretKey secretKey = keyGen. generateKey();


1 Answers

This is all outdated. The only remcoomended algorithm ist Argon2id. It is in the newer Versions of Bouncycastle: https://www.bouncycastle.org/latest_releases.html

If you run out of memory, use "-Xmx8G" in the execution arguments.

private SecretKey genKey(char[] passwordChars, byte[] saltBytes) {
SecretKey aesKey;
    int aesKeyLen = 16; //key len in bytes
    int version = Argon2Parameters.ARGON2_VERSION_13;
    int iterations = 1;
    int memory = 22; // 20 = 1 GB -> 22=4GB
    int parallelism = 16; //double CPU core
    Argon2Parameters.Builder builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
            .withVersion(version).withIterations(iterations).withMemoryPowOfTwo(memory) // use 2^(memory) KB
            .withParallelism(parallelism).withSalt(saltBytes);
    Argon2BytesGenerator gen = new Argon2BytesGenerator();
    gen.init(builder.build());
    byte[] result = new byte[aesKeyLen];
    gen.generateBytes(passwordChars, result, 0, result.length);
    aesKey = new SecretKeySpec(result, "AES");
//clear to free RAM
    builder = null;
    gen = null;
    System.gc();
return aesKey;
}
like image 176
Karl Avatar answered Oct 15 '22 10:10

Karl