加密jdbc串連以及表敏感欄位,加密jdbc欄位

來源:互聯網
上載者:User

加密jdbc串連以及表敏感欄位,加密jdbc欄位
本文使用Jasypt與Hibernate整合,透明加密個人資料、私人資訊等重要資料,避免其他擁有許可權的人可以使用終端訪問資料庫以及關鍵表內容。大致思路是:先用jasypt加密串連資料庫的url、username、password、driverClass,自訂DruidConnectionProvider解密這些屬性,然後串連資料庫;實體entity欄位的加密是通過自訂Hibernate UserType實現。

前言

開發環境:Eclipse+JDK8+Hibernate5

參考資料:http://www.jasypt.org/hibernate.html

demo下載:http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId=478

加密url、使用者名稱、密碼、驅動類

public void generateJDBCString() {        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();        encryptor.setAlgorithm(ParamEncryptor.ALGORITHM);        encryptor.setProvider(new BouncyCastleProvider());// none-JCE        encryptor.setPassword(ParamEncryptor.ALGORITHM_PASSWORD);         String driverClass = "org.mariadb.jdbc.Driver";        String url = "jdbc:mariadb://localhost:3306/mysql";        String username = "test";        String pwd = "123456";                 String encryptDriverClass = encryptor.encrypt(driverClass);        String encryptUrl = encryptor.encrypt(url);        String encryptUsername = encryptor.encrypt(username);        String encryptPwd = encryptor.encrypt(pwd);        System.out.println("driver class: "+encryptDriverClass);        System.out.println("url: "+encryptUrl);        System.out.println("username: "+encryptUsername);        System.out.println("pwd: "+encryptPwd);    }
自訂資料庫連接池串連提供者DruidConnectionProvider,解密url、使用者名稱、密碼、驅動類

public class EncryptedDruidConnectionProvider extends DruidConnectionProvider {     /**     *      */    private static final long serialVersionUID = -409669485957486646L;         public EncryptedDruidConnectionProvider() {        super();    }     @SuppressWarnings({"unchecked", "rawtypes"})    @Override    public void configure(Map props) {         final String encryptorRegisteredName = (String) props.get("hibernate.connection.encryptor_registered_name");         final HibernatePBEEncryptorRegistry encryptorRegistry = HibernatePBEEncryptorRegistry.getInstance();        final PBEStringEncryptor encryptor = encryptorRegistry.getPBEStringEncryptor(encryptorRegisteredName);         if (encryptor == null) {            throw new EncryptionInitializationException("No string encryptor registered for hibernate " + "with name \"" + encryptorRegisteredName + "\"");        }         // Get the original values, which may be encrypted        final String driver = (String) props.get(DruidDataSourceFactory.PROP_DRIVERCLASSNAME);        final String url = (String) props.get(DruidDataSourceFactory.PROP_URL);        final String user = (String) props.get(DruidDataSourceFactory.PROP_USERNAME);        final String password = (String) props.get(DruidDataSourceFactory.PROP_PASSWORD);         // Perform decryption operations as needed and store the new values        if (PropertyValueEncryptionUtils.isEncryptedValue(driver)) {            props.put(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, PropertyValueEncryptionUtils.decrypt(driver, encryptor));        }        if (PropertyValueEncryptionUtils.isEncryptedValue(url)) {            props.put(DruidDataSourceFactory.PROP_URL, PropertyValueEncryptionUtils.decrypt(url, encryptor));        }        if (PropertyValueEncryptionUtils.isEncryptedValue(user)) {            props.put(DruidDataSourceFactory.PROP_USERNAME, PropertyValueEncryptionUtils.decrypt(user, encryptor));        }        if (PropertyValueEncryptionUtils.isEncryptedValue(password)) {            props.put(DruidDataSourceFactory.PROP_PASSWORD, PropertyValueEncryptionUtils.decrypt(password, encryptor));        }         // Let Hibernate do the rest        super.configure(props);    } }
配置hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <property name="hibernate.connection.encryptor_registered_name">hibernateStringEncryptor</property>                 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        <property name="hibernate.connection.provider_class">com.wisdomdd.dataEncryption_hibernate.util.EncryptedDruidConnectionProvider</property>        <property name="url">ENC(xZ+JDmEcwFauyvMrXhRyFloaJ3JRQ30pCGx00Y9jS8xugKy7etWhEzJXHa+37K9J)</property>        <property name="username">ENC(uWnvfEFEOPFEaelwwiYK0Q==)</property>        <property name="password">ENC(kRKRp1R3xeeFd510BOnwcg==)</property>        <property name="driverClassName">ENC(N658dS3sxVcjUG8uNdJKuDjlvyUUdHwoGVUnT+vl0/k=)</property>        <property name="hibernate.jdbc.batch_size">20</property>        <property name="hibernate.jdbc.fetch_size">30</property>        <property name="show_sql">true</property>        <property name="format_sql">true</property>        <!-- 配置初始化大小、最小、最大 -->        <property name="initialSize">1</property>        <property name="minIdle">1</property>        <property name="maxActive">20</property>        <!-- 配置擷取串連等待逾時的時間 -->        <property name="maxWait">60000</property>        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑串連,單位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis">60000</property>        <!-- 配置一個串連在池中最小生存的時間,單位是毫秒 -->        <property name="minEvictableIdleTimeMillis">300000</property>        <property name="validationQuery">SELECT 'x'</property>        <property name="testWhileIdle">true</property>        <property name="testOnBorrow">false</property>        <property name="testOnReturn">false</property>        <!-- 開啟PSCache,並且指定每個串連上PSCache的大小 -->        <property name="poolPreparedStatements">true</property>        <property name="maxPoolPreparedStatementPerConnectionSize">20</property>        <!-- 配置監控統計攔截的filters,去掉後監控介面sql無法統計 -->        <property name="filters">stat</property>        <!-- 配置註解映射類 -->        <mapping class="com.wisdomdd.dataEncryption_hibernate.entity.Account" />    </session-factory></hibernate-configuration>

使用註解映射實體,Jasypt加解密資料

首先用一個@TypeDef註解來定義加密類型,這個註解可以在持久實體類中,或者在一個單獨的package-info.java檔案中的@TypeDefs聲明中:

@TypeDef(    name =“encryptedString”,    typeClass = EncryptedStringType.class,    parameters = {         @Parameter(name =“encryptorRegisteredName”,value =“myHibernateStringEncryptor”)    } )

...然後簡單地將我們的屬性與已經聲明的類型進行映射:
 @Type(type =“encryptedString”)    public String getAddress(){         return address;     }

結束語

以上是部分代碼,完整運行執行個體,請下載附件Demo。

  demo下載:http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId=478



相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.