Java加密數據庫

一.背景

  數據庫配置以明文方式展現如圖,會形成安全隱患,若是有黑客入侵會形成密碼泄露,信息竊取和破壞等。java

二.加密步驟

  1.對數據庫信息加密:

    對數據庫中的帳號和密碼信息進行加密(選擇一種算法)而後替換掉原來的明文數據庫配置信息。算法

   2.解密:

    在Spring讀取使用配置文件時進行解密成明文。spring

三.編碼實現

  1.加密類實現:(採用DES算法)

    1.1DES算法介紹:

      DES是一種對稱算法,即加密和解密使用的是相同的算法。數據庫

      詳細介紹:http://www.noobyard.com/article/p-byncdmix-y.html數組

    1.2實現:

      得到加密後的帳號密碼後替換原先的數據庫明文配置。安全

      DESUtils.Java:dom

 1 import java.security.Key;
 2 import java.security.SecureRandom;
 3 
 4 import javax.crypto.Cipher;
 5 import javax.crypto.KeyGenerator;
 6 
 7 import sun.misc.BASE64Decoder;
 8 import sun.misc.BASE64Encoder;
 9 
10 public class DESUtils {
11 
12     private static Key key;
13     // 設置密鑰key
14     private static String KEY_STR = "myKey";
15     private static String CHARSETNAME = "UTF-8";
16     private static String ALGORITHM = "DES";
17 
18     // 靜態代碼塊
19     static {
20         try {
21             // 生成DES算法對象
22             KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
23             // 運用SHA1安全策略
24             SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
25             // 設置上密鑰種子
26             secureRandom.setSeed(KEY_STR.getBytes());
27             // 初始化基於SHA1的算法對象
28             generator.init(secureRandom);
29             // 生成密鑰對象
30             key = generator.generateKey();
31             generator = null;
32         } catch (Exception e) {
33             throw new RuntimeException(e);
34         }
35     }
36 
37     /**
38      * 獲取加密後的信息
39      * 
40      * @param str
41      * @return
42      */
43     public static String getEncryptString(String str) {
44         // 基於BASE64編碼,接收byte[]並轉換爲String
45         BASE64Encoder base64encoder = new BASE64Encoder();
46         try {
47             // 按UTF-8編碼
48             byte[] bytes = str.getBytes(CHARSETNAME);
49             // 獲取加密對象
50             Cipher cipher = Cipher.getInstance(ALGORITHM);
51             // 初始化密碼信息
52             cipher.init(Cipher.ENCRYPT_MODE, key);
53             // 加密
54             byte[] doFinal = cipher.doFinal(bytes);
55             // byte[] to encode好的String並返回
56             return base64encoder.encode(doFinal);
57         } catch (Exception e) {
58             // TODO: handle exception
59             throw new RuntimeException(e);
60         }
61     }
62 
63     /**
64      * 獲取解密後的信息
65      * 
66      * @param str
67      * @return
68      */
69     public static String getDecryptString(String str) {
70         //基於BASE64編碼,接收byte[]並轉換爲String
71         BASE64Decoder base64decoder = new BASE64Decoder();
72         try {
73             //將字符串decode爲byte[]
74             byte[] bytes = base64decoder.decodeBuffer(str);
75             //獲取解密對象
76             Cipher cipher = Cipher.getInstance(ALGORITHM);
77             //初始化解密信息
78             cipher.init(Cipher.DECRYPT_MODE, key);
79             //解密
80             byte[] doFinal = cipher.doFinal(bytes);
81             //返回解密以後的信息
82             return new String(doFinal, CHARSETNAME);
83         } catch (Exception e) {
84             // TODO: handle exception
85             throw new RuntimeException(e);
86         }
87     }
88 
89     public static void main(String[] args) {
90         System.out.println(getEncryptString("root"));
91         System.out.println(getEncryptString("123654"));
92         
93     }
94 
95 }
View Code

   2.配置文件解析類:

     EncryptPropertyPlaceholderConfigurer.java:ide

 1 import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
 2 
 3 public class EncryptPropertyPlaceholderConfigurer extends
 4         PropertyPlaceholderConfigurer {
 5     //須要加密的字段數組
 6     private String[] encryptPropNames = { "jdbc.username", "jdbc.password" };
 7     /**
 8      * 對關鍵的屬性進行轉換
 9      */
10     @Override
11     protected String convertProperty(String propertyName, String propertyValue) {
12         if (isEncryptProp(propertyName)) {
13             //對已加密的字段進行階段工做
14             String decryptValue = DESUtils.getDecryptString(propertyValue);
15             return decryptValue;
16         } else {
17             return propertyValue;
18         }
19     }
20     /**
21      * 該屬性是否已經加密
22      * @param propertyName
23      * @return
24      */
25     private boolean isEncryptProp(String propertyName) {
26         //若等於須要加密的field,則進行加密
27         for (String encryptpropertyName : encryptPropNames) {
28             if (encryptpropertyName.equals(propertyName))
29                 return true;
30         }
31         return false;
32     }
33 }
View Code

     未修改前默認使用:編碼

<context:property-placeholder location="classpath:jdbc.properties" />

 

    配置爲本身寫的:經過文件解析類將密文解析爲明文賦值給對應字段。加密

    <bean class="com.swpu.o2o.util.EncryptPropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <!-- 須要解密的文件 -->
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
        <!-- 設置編碼爲UTF-8 -->
        <property name="fileEncoding" value="UTF-8"></property>
    </bean>