javaproperties-filekey-generator

How to add GeneratedKey to config.properties 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
KEY=\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000

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 = "config.properties";
    try {
        OutputStream out = new FileOutputStream(propertiesFileName);
        properties.setProperty(x, z);
        properties.store(out, null);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

 //THIS METHOD ADDING PROP TO PROPERTIES FILE
        addProperties("KEY", new String(key));

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

}

Thanks for help.All answers acceptable.


Solution

  • 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 java.security.Key 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");