为了能达到使用 spring dbcp配置时,也有类似密码加密的功能,运行期进行密码decode,最后进行数据链接
实现方式很简单,分析jboss的对应SecureIdentityLoginModule的实现,无非就是走了Blowfish加密算法,自己拷贝实现一份。
- private static String encode(String secret) throws NoSuchPaddingException, NoSuchAlgorithmException,
- InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
- byte[] kbytes = "jaas is the way".getBytes();
- SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
- Cipher cipher = Cipher.getInstance("Blowfish");
- cipher.init(Cipher.ENCRYPT_MODE, key);
- byte[] encoding = cipher.doFinal(secret.getBytes());
- BigInteger n = new BigInteger(encoding);
- return n.toString(16);
- }
- private static char[] decode(String secret) throws NoSuchPaddingException, NoSuchAlgorithmException,
- InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
- byte[] kbytes = "jaas is the way".getBytes();
- SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
- BigInteger n = new BigInteger(secret, 16);
- byte[] encoding = n.toByteArray();
- Cipher cipher = Cipher.getInstance("Blowfish");
- cipher.init(Cipher.DECRYPT_MODE, key);
- byte[] decode = cipher.doFinal(encoding);
- return new String(decode).toCharArray();
- }
最后的配置替换为:
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- ......
- <property name="password"><!-- 注意多了一层转化,将密码串调用decode解密为最初的数据库密码 -->
- <bean class="com.xxxxx.EncryptDBPasswordFactory">
- <property name="password" value="${xxxx.password.encrypted}" />
- </bean>
- </property>
- ........
- </bean>
--------------------------------------------