加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 01:06:41 所属栏目:Java 来源:网络整理
导读:我正在尝试加密解密密码和这些生成密钥到目前为止都很好.现在我需要将此密钥存储在属性文件中,但是当我添加密钥时,它看起来像这样: #Tue Nov 01 08:22:52 EET 2016KEY=u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u00

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

#Tue Nov 01 08:22:52 EET 2016
KEY=u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000u0000

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

并且我的代码中有一部分=

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

}

谢谢你的帮助.所有答案都可以接受.

最佳答案
KeyGenerator#generateKey()的返回类型为SecretKey,来自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(decodingKey,decodingKey.length,“AES”);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读