加密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



相關文章

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。