spring 配置中,資料庫相關資訊如何加密放在屬性檔案中
項目中,我們一般會對一些配置資訊加密放到屬性檔案,或者其他地方,比如資料庫的密碼或者url、使用者名稱都可以加密放到屬性檔案內,在程式啟動後,一般會有對應的解密機制,還原資訊,去串連資料庫等。
在spring架構中,讀取屬性配置的類那就是org.springframework.beans.factory.config.PropertyPlaceholderConfigurer。
所以,一般的資訊解密功能是擴充這個類實現的。不過,現在jasypt庫也幫我們實現了這樣的功能 (http://www.jasypt.org/ ), 可以參看文檔,如何設定項目。
本例子中,用的是org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer,它也是擴充的spring屬性配置類而實現的加密機制。
配置例子:
<span style="font-size:18px;"><bean id="environmentVariablesConfiguration" class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig"> <property name="algorithm" value="PBEWithMD5AndDES" /> <property name="password" value="root" /> </bean> <bean id="configurationEncryptor" class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor"> <property name="config" ref="environmentVariablesConfiguration" /> </bean> <bean id="propertyConfigurer" class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer"> <constructor-arg ref="configurationEncryptor" /> <property name="locations"> <list> <value>classpath:/JasyptProp/Jasypt.properties</value> </list> </property> <property name="fileEncoding" value="utf-8" /> </bean></span>
其中,加密參數比如演算法,我們可以自行配置。
詳細測試代碼見:https://github.com/sdcuike/springmvc-ajax/blob/master/springMvc/src/test/java/com/doctor/Jasypt/JasyptTest.java