如何将GeneratedKey添加到config.properties文件?

时间:2016-11-01 06:46:22

标签: java properties-file key-generator

我试图加密&解密密码和这些生成密钥到目前为止都很好。现在我需要将此密钥存储在属性文件中,但是当我添加密钥时它看起来像这样:

#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

所以我怀疑我的代码可能有问题?!?!

我的代码中有一部分=

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();
    }

}

感谢您的帮助。所有答案均可接受。

1 个答案:

答案 0 :(得分:3)

KeyGenerator#generateKey()的返回类型为SecretKey,来自javadocs

  

实现此接口的键将字符串RAW作为其返回   编码格式(参见getFormat),并返回原始密钥字节   getEncoded方法调用的结果。 (getFormat和getEncoded   方法继承自java.security.Key父接口。)

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");