0

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.

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • Refer to the key generation section here: https://stackoverflow.com/a/53015144/1235935 Once you get the key bytes, encode it in Base64. The answer for Base64 encoding is also provided in this answer. – Saptarshi Basu Jan 15 '19 at 06:58

1 Answers1

2

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

gusto2
  • 11,210
  • 2
  • 17
  • 36