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?
We can use the SecretKeyFactory class with the PBKDF2WithHmacSHA256 algorithm for generating a key from a given password.
KeyGenerator keyGen = KeyGenerator. getInstance("AES"); keyGen. init(256); // for example SecretKey secretKey = keyGen. generateKey();
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;
}
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