How can I create my own keys for encrypting a string using AES algorithm in Java instead of using
KeyGenerator kgen = KeyGenerator.getInstance("AES");
which creates a random key?
kgen is not a key, actual key is your SecretKeySpec object. You can create your key using raw bytes...see the below example...
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
byte raw[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
SecretKeySpec spec = new SecretKeySpec(raw, "AES");
//SecretKey key = kgen.generateKey();
//byte keybytes[] = key.getEncoded();
//SecretKeySpec spec = new SecretKeySpec(keybytes, "AES");
SecretKeySpec as a key (it implements the SecretKey interface) if you have an algorithm that takes random bytes as a key. This is at least true for AES and DES ABC keys (for use in DESede), in the latter the parity bits are ignored. If you store a key as a field, I would still use the SecretKeyFactory to create a "fail fast" scenario.