java_fortify Scan:

问题:
1.Key Management: Hardcoded Encryption Key

问题解释:
问题1.秘钥使用硬编码方式。

解决方案:
使用Keystore生成存储AES密钥文件

使用Keystore生成存储AES密钥文件工具类(JDK1.8):

package com.study.util;

import com.studymon.Consts;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateException;

/**
 * keystore生成存储AES密钥文件
 * 
 */
public class KeyStoreUtils {

    /**
     * 功能:把秘钥保存到秘钥库文件中
     * @param key  秘钥
     * @param alias 别名
     * @param pdKey 秘钥密码
     * @param pdKeyStore 秘钥库密码
     * @param ksFileName 秘钥库文件名称
     */
    private static void initKeyStore(Key key,String alias,String pdKey,String pdKeyStore,String ksFileName) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        keyStore.load(null, null);
        // alias为别名,pd为其密码
        keyStore.setKeyEntry(alias, key, pdKey.toCharArray(), null);
        // pd密钥库密码
        String path = KeyStoreUtils.class.getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream(path + ksFileName);
            keyStore.store(fos, pdKeyStore.toCharArray());
        }finally{
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 功能:从秘钥库文件中取出秘钥
     * @param alias 别名
     * @param pdKey 秘钥密码
     * @param pdKeyStore 秘钥库密码
     * @param ksFileName 秘钥库文件名称
     */
    private static Key acquireKeyStore(String alias,String pdKey,String pdKeyStore,String ksFileName) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException, UnrecoverableEntryException {
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        String path = KeyStoreUtils.class.getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串
        FileInputStream fis = null;
        try{
            fis = new FileInputStream(path + ksFileName);
            keyStore.load(fis, pdKeyStore.toCharArray());
            Key key = keyStore.getKey(alias,pdKey.toCharArray());
            return key;
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

注:本工具生成的keystore文件在resource路径下,此路径可以根据本人需要修改

参考资料:https://blog.csdn/weixin_46505978/article/details/119784021?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-3-119784021-null-null.pc_agg_new_rank&utm_term=aes+java+%E5%AF%86%E9%92%A5%E5%AD%98%E5%82%A8&spm=1000.2123.3001.4430

更多推荐

java fortify硬编码秘钥漏洞使用KeyStore解决