SSM achieve mysql database account password to log ciphertext

introduction

      Our company is engaged in the application of some of the classified information security research and development projects, a total of three steps, compared to the general corporate and general projects, more stringent requirements for information security, the leaders of the amount of data and the user's user name and password information ciphertext are required to configure and storage, which involves jdbc.properties file database user name and password is the same, you need to configure asked the ciphertext, when connecting the reloading operation of the database connection decrypted plaintext the following is the implementation process, a total of three steps.

First, create a class DESUtil

Providing a custom key encryption method for decrypting.

 1 package com.hzdy.DCAD.common.util;
 2 
 3 import sun.misc.BASE64Decoder;
 4 import sun.misc.BASE64Encoder;
 5 import javax.crypto.Cipher;
 6 import javax.crypto.KeyGenerator;
 7 import java.security.Key;
 8 import java.security.SecureRandom;
 9 
10 /**
11  * Created by Wongy on 2019/8/8.
12  */
13 public class DESUtil {
14     private static Key key;
15     //自己的密钥
16     private static String KEY_STR = "mykey";
17 
18     static {
19         try {
20             KeyGenerator generator = KeyGenerator.getInstance("DES");
21             SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
22             secureRandom.setSeed(KEY_STR.getBytes());
23             generator.init(secureRandom);
24             key = generator.generateKey();
25             generator = null;
26         } catch (Exception e) {
27              the throw  new new a RuntimeException (E);
 28          }
 29      }
 30  
31 is      / ** 
32       * encrypt a string and returns the encrypted string BASE64
 33 is       *
 34 is       * @param STR
 35       * @return 
36       * @see [Class, method #, members of category #]
 37 [       * / 
38 is      public  static String getEncryptString (String STR) {
 39          Base64Encoder Base64Encoder = new new Base64Encoder ();
 40          the try {
 41 is              byte[] strBytes = str.getBytes("UTF-8");
42             Cipher cipher = Cipher.getInstance("DES");
43             cipher.init(Cipher.ENCRYPT_MODE, key);
44             byte[] encryptStrBytes = cipher.doFinal(strBytes);
45             return base64Encoder.encode(encryptStrBytes);
46         } catch (Exception e) {
47             throw new RuntimeException(e);
48         }
49 
50     }
51 
52     /**
53      * 对BASE64加密字符串进行解密
54      *
55      */
56     public static String getDecryptString(String str) {
57         BASE64Decoder base64Decoder = new BASE64Decoder();
58         try {
59             byte[] strBytes = base64Decoder.decodeBuffer(str);
60             Cipher cipher = Cipher.getInstance("DES");
61             cipher.init(Cipher.DECRYPT_MODE, key);
62             byte[] encryptStrBytes = cipher.doFinal(strBytes);
63             return new String(encryptStrBytes, "UTF-8");
64         } catch (Exception e) {
65             throw new RuntimeException(e);
66         }
67 
68     }
69 
70 
71     public static void main(String[] args) {
72         String name = "dbuser";
73         String password = "waction2016";
74         String encryname = getEncryptString(name);
75         String encrypassword = getEncryptString(password);
76         System.out.println("encryname : " + encryname);
77         System.out.println("encrypassword : " + encrypassword);
78 
79         System.out.println("name : " + getDecryptString(encryname));
80         System.out.println("password : " + getDecryptString(encrypassword));
81     }
82 }

Second, create a class EncryptPropertyPlaceholderConfigurer

Associated with the profile.

. 1  Package com.hzdy.DCAD.common.util;
 2  
. 3  Import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
 . 4  
. 5  public  class EncryptPropertyPlaceholderConfigurer the extends The PropertyPlaceholderConfigurer {
 . 6      // KEY file properties required to maintain a straight configuration 
. 7      Private String [] = {encryptPropNames "jdbc.username", "jdbc.password" };
 . 8  
. 9      @Override
 10      protected String convertProperty (propertyName String, String the propertyValue) {
 . 11  
12 is          // If the attribute was found in the encryption attribute list   
13         if (isEncryptProp(propertyName)) {
14             String decryptValue = DESUtil.getDecryptString(propertyValue);
15             System.out.println(decryptValue);
16             return decryptValue;
17         } else {
18             return propertyValue;
19         }
20 
21     }
22 
23     private boolean isEncryptProp(String propertyName) {
24         for (String encryptName : encryptPropNames) {
25             if (encryptName.equals(propertyName)) {
26                 return true;
27             }
28         }
29         return false;
30     }
31 } 

Third, modify the configuration file jdbc.properties 

1  prior ciphering configuration #
 2  # = com.mysql.jdbc.Driver jdbc.driver
 . 3  # = jdbc.user the root
 . 4  # jdbc.password = the root
 . 5  # jdbc.url = JDBC: MySQL: // localhost: 3306 / Bookstore
 . 6  
7  after # ciphering configuration
 . 8  jdbc.driver = com.mysql.jdbc.Driver
 . 9  jdbc.user = Ov4j7fKiCzY =
 10  jdbc.password Ov4j7fKiCzY = =
 . 11 jdbc.url = JDBC: MySQL: // localhost: 3306 / Bookstore

Fourth, the spring-content.xml modify configuration files

1  the spring-context in the
 2  < context: Property-placeholder LOCATION = "CLASSPATH: .properties"  /> 
. 3  modify
 . 4  < the bean class = "com.hzdy.DCAD.common.util.EncryptPropertyPlaceholderConfigurer" P: locations = " the CLASSPATH:. * the Properties " /> 
5 // note that there is only one read configuration files bean, otherwise the system will only read the front

   Note : If you find that the configuration of the ciphertext username and password can be loaded and decryption is successful, but when the last connection is still in encrypted connection and error, which may involve memory problems preloaded, the project started, the program encrypts the ciphertext user name and password, even if the final decryption is successful, the last connection but still read encrypted database, this time we can rewrite their own method of connection pool, so spring-content.xml load connection pool overridden method, and connection ahead of time and then decrypt. 

 1 package com.thinkgem.jeesite.common.encrypt;
 2 
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5 import java.util.Properties;
 6 
 7 import javax.security.auth.callback.PasswordCallback;
 8 import com.alibaba.druid.util.DruidPasswordCallback;
 9 
10 /**
11  */
12 @SuppressWarnings("serial")
13 public class DruidDataSource extends com.alibaba.druid.pool.DruidDataSource {
14     
15     public PhysicalConnectionInfo createPhysicalConnection() throws SQLException {
16         String url = this.getUrl();
17         Properties connectProperties = getConnectProperties();
18 
19         String user;
20         if (getUserCallback() != null) {
21             user = getUserCallback().getName();
22         } else {
23             user = getUsername();
24         }
25         //DES解密
26         user = DESUtils.getDecryptString(user);
27         String password = DESUtils.getDecryptString(getPassword());
28         
29         PasswordCallback passwordCallback = getPasswordCallback();
30 
31         if (passwordCallback != null) {
32             if (passwordCallback instanceof DruidPasswordCallback) {
33                 DruidPasswordCallback druidPasswordCallback = (DruidPasswordCallback) passwordCallback;
34 
35                 druidPasswordCallback.setUrl(url);
36                 druidPasswordCallback.setProperties(connectProperties);
37             }
38 
39             char[] chars = passwordCallback.getPassword();
40             if (chars != null) {
41                 password = new String(chars);
42             }
43         }
44 
45         Properties physicalConnectProperties = new Properties();
46         if (connectProperties != null) {
47             physicalConnectProperties.putAll(connectProperties);
48         }
49 
50         if (user != null && user.length() != 0) {
51             physicalConnectProperties.put("user", user);
52         }
53 
54         if (password != null && password.length() != 0) {
55             physicalConnectProperties.put("password", password);
56         }
57 
58         Connection conn;
59 
60         long connectStartNanos = System.nanoTime();
61         long connectedNanos, initedNanos, validatedNanos;
62         try {
63             conn = createPhysicalConnection(url, physicalConnectProperties);
64             connectedNanos = System.nanoTime();
65 
66             if (conn == null) {
67                 throw new SQLException("connect error, url " + url + ", driverClass " + this.driverClass);
68             }
69 
70             initPhysicalConnection(conn);
71             initedNanos = System.nanoTime();
72 
73             validateConnection(conn);
74             validatedNanos = System.nanoTime();
75             
76             setCreateError(null);
77         } catch (SQLException ex) {
78             setCreateError(ex);
79             throw ex;
80         } catch (RuntimeException ex) {
81             setCreateError(ex);
82             throw ex;
83         } catch (Error ex) {
84             createErrorCount.incrementAndGet();
85             throw ex;
86         } finally {
87             long nano = System.nanoTime() - connectStartNanos;
88             createTimespan += nano;
89         }
90 
91         return new PhysicalConnectionInfo(conn, connectStartNanos, connectedNanos, initedNanos, validatedNanos);
92     }
93 }

Database connections modified configuration file spring-content.xml

1  before the modification #
 2  <-! <The bean ID = "the dataSource" class = "com.alibaba.druid.pool.DruidDataSource" = the init-Method "the init" the destroy-Method = "Close"> -> 
. 3  
. 4  # after modifying
 . 5  < the bean ID = "the dataSource" class = "com.thinkgem.jeesite.common.encrypt.DruidDataSource" 
. 6          the init-Method = "the init" the destroy-Method = "Close" > 
. 7          <-! data source driver class do not write, Druid automatically based on default URL identification DriverClass -> 
. 8          < Property name = "driverClassName" value="${jdbc.driver}" />
10         <!-- 基本属性 url、user、password -->
11         <property name="url" value="${jdbc.url}" />
12         <property name="username" value="${jdbc.username}" />
13         <property name="password" value="${jdbc.password}" />
14 
15     </bean>

So far, the ciphertext database connection configuration is complete!

Guess you like

Origin www.cnblogs.com/zhaosq/p/11321157.html