1. 程式人生 > >properties檔案加密處理方法

properties檔案加密處理方法

1.在application.xml檔案中載入config.properties檔案方式(會將config.properties的配置載入進來)
<bean class="com.paic.utils.EncryptPropertyConfigurer這個工具類
">
  <property name = "location" value="classpath:config.properties的配置載入進來"></property>
  <property name = "fileEncoding" value="UTF-8"></property>
</bean>2.加密方法
/**
 * 密碼工具類
 * Created by Li.fang on 2014/11/13.
 */
public class CipherUtils {    private static Logger logger = LoggerFactory.getLogger(CipherUtils.class);    //指定DES加密解密所用金鑰
    private static Key key;    private static String STR_SALT = "APLUS OFFICE SYSTEM";    private static final String GENERATOR_DES = "DES";    private static final String ENCODING_UTF8 = "UTF-8";    private static final int CIPHER_COUNT = 5;    static {
        try {
            KeyGenerator generator = KeyGenerator.getInstance(GENERATOR_DES);
            generator.init(new SecureRandom(STR_SALT.getBytes()));
            key = generator.generateKey();
            generator = null;
        }catch (NoSuchAlgorithmException e){
            logger.warn("Cryptographic failure");
            throw new RuntimeException(e);
        }
    }
    /**
     * 對字串進行DES加密,返回BASE64編碼的加密字串
     * @param str 需要加密的字串
     * @return 加密後的字串
     */
    public static String getEncryptBase64String(String str){
//        BASE64Encoder base64Encoder = new BASE64Encoder();
        try{
            byte[] strBytes = str.getBytes(ENCODING_UTF8);
            Cipher cipher= Cipher.getInstance(GENERATOR_DES);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            return Base64.encodeBase64String(encryptStrBytes);
        }catch (Exception e){
            logger.warn("Cryptographic failure");
            throw new RuntimeException(e);
        }
    }    /**
     * 對BASE64編碼的加密字串進行解密,返回解密後的字串
     * @param str BASE64加密字串
     * @return 解密後的字串
     */
    public static String getDecryptString(String str){
//        BASE64Decoder base64Decoder = new BASE64Decoder();
        try{
            byte[] strBytes = Base64.decodeBase64(str);
            Cipher cipher= Cipher.getInstance(GENERATOR_DES);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decryptStrBytes = cipher.doFinal(strBytes);
            return new String(decryptStrBytes, ENCODING_UTF8);
        }catch (Exception e){
            logger.warn("Decryption failure");
            throw new RuntimeException(e);
        }
    }}3.寫EncryptPropertyConfigurer這個工具類package com.aplus.method;import com.aplus.utils.CipherUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;/**
 * 繼承PropertyPlaceholderConfigurer,配置支援密文屬性的屬性檔案
 * Created by li.fang on 2014/11/13.
 */
public class EncryptPropertyConfigurer extends PropertyPlaceholderConfigurer{    private Logger logger = LoggerFactory.getLogger(EncryptPropertyConfigurer.class);    //需要解密的屬性
    private String[] encryptPropNames = {"jdbc.url","jdbc.username","jdbc.password"};    /**
     * 對特定屬性的屬性值進行轉換
     * @param propertyName 屬性名稱
     * @param propertyValue 屬性值
     * @return
     */
    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        logger.info("The properties name is : {}, value is : ", propertyName, propertyValue);
        if(isEncryptProp(propertyName)){
            String decryptValue = CipherUtils.getDecryptString(propertyValue);
            logger.info(decryptValue);
            return decryptValue;
        }else{
            return propertyValue;
        }
    }    /**
     * 判斷屬性是否需要解密
     * @param propertyName
     * @return
     */
    private boolean isEncryptProp(String propertyName){
        for(String encryptPropName : encryptPropNames){
            if(StringUtils.equals(encryptPropName,propertyName)){
                return true;
            }
        }
        return false;
    }
}使用URL下載到指定的檔案中:
使用URL下載指定的檔案儲存到指定的資料夾中。
/*
 * 使用URL下載指定的檔案儲存到指定的資料夾中。
 * 類 URL 代表一個統一資源定位符,它是指向網際網路“資源”的指標。
 * 資源可以是簡單的檔案或目錄,也可以是對更為複雜的物件的引用,
 * 例如對資料庫或搜尋引擎的查詢。
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class URLDemo {
public static void main(String[] args) {
try {
DownLoadUtil.download("指定的網站", "儲存的檔名", "儲存到指定地方");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class DownLoadUtil{
public static void download
(String urlString,String fileName,String savePath)throws IOException {
URL url=new URL(urlString);
/* URLConnection conn=url.openConnection();
InputStream is=conn.getInputStream();*/
//使用一條指令代替上面的兩條指令
InputStream is=url.openStream();
byte[] buff=new byte[1024];
int len=0;
//讀操作
File file=new File(savePath);
if (!file.exists()) {
file.mkdirs();}
//寫操作
OutputStream os=new FileOutputStream(file.getAbsolutePath()+"\\"+fileName);
//一邊讀一邊寫
while ((len=is.read(buff))!=-1) {
os.write(buff, 0, len);//把讀到寫到指定的數組裡面
//釋放資源
os.close();
is.close();
}
}
}