How to add GeneratedKey file to config.properties file?

I am trying to encrypt and decrypt the password and for these generation keys it is still so good. Now I need to save this key in the properties file, but when I add the key, it looks 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 that something might be wrong from my code?!?!

And there is 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 the help. All answers are acceptable.

+5
source share
1 answer

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

Keys that implement this interface will return the RAW string as (see getFormat) and return the raw key bytes as the result of calling the getEncoded method. (The GetFormat and getEncoded methods inherit from the parent java.security.Key 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");

+2
source

Source: https://habr.com/ru/post/1259078/


All Articles