1

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?

2 Answers 2

4

By using a SecretKeySpec:

SecretKey key = new SecretKeySpec(bytes, "AES");
Sign up to request clarification or add additional context in comments.

Comments

2

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");

2 Comments

Note that you can directly use 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.
Ohk...thnks for the vital info..:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.