Coder ACJHP Coder ACJHP - 1 year ago 63
Java Question

How to add GeneratedKey to file?

I'm trying to encrypt & decrypt password and for these generating key so far so good.Now I need to store this key in properties file but when I add the key it look like this :

#Tue Nov 01 08:22:52 EET 2016

So I suspect from my code maybe something wrong ?!?!

And there is a part of my code =

private byte[] key = new byte[16];

public void addProperties(String x, String z) {
Properties properties = new Properties();
String propertiesFileName = "";
try {
OutputStream out = new FileOutputStream(propertiesFileName);
properties.setProperty(x, z);, null);
} catch (IOException e) {

public void generateKey() {
KeyGenerator keygen;
SecretKey secretKey;
byte[] keybyte = new byte[64];
try {
keygen = KeyGenerator.getInstance("AES");
secretKey = keygen.generateKey();
keybyte = secretKey.getEncoded();
key = keybyte;

addProperties("KEY", new String(key));

} catch (NoSuchAlgorithmException e) {


Thanks for help.All answers acceptable.

Answer Source

KeyGenerator#generateKey() has return type of SecretKey and from javadocs

Keys that implement this interface return the string RAW as their encoding format (see getFormat), and return the raw key bytes as the result of a getEncoded method call. (The getFormat and getEncoded methods are inherited from the parent interface.)

So you need to convert them and there is already asked question on this

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

SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download