Mousami Nath
Mousami Nath

Reputation: 1

How to generate a AES 128 bit key in Java. I want something like this. Es8NxqG/f3VMzcd9mrPSQQ==

I tried below.

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey skey = kgen.generateKey();
String s = new String(skey.getEncoded());

But not getting in the required format. Would really appreciate any help. Thanks in advance.

Upvotes: 0

Views: 547

Answers (1)

gusto2
gusto2

Reputation: 12085

skey.getEncoded()

getEncoded method returns a byte array. You cannot just create a String from byte array, most of the bytes would represent non-printable characters.

What you ask for is Base64 encoding - it is a way to represent binary data as printable character.

You can use the default Java Base64 encoder https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html to encode and decode binary data.

String encodedKey = Base64.getEncoder().encodeToString(skey.getEncoded());

There are other encoder implementations used as well, such as commons-codec

Please note - in crypto all primitives and operations (keys, encryption, digest, signing, ..) are working on top of byte arrays, encoding is used only to represent data as printable string

Upvotes: 2

Related Questions