在我们日常的开发中,必须要连接数据库,但是数据库的账户和密码有么有加密呢?在这里我们使用DES对称加密算法
步骤
- 编写一个DESUtil,我从网上搞了一个过来,贴在这里
import java.security.Key; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; @SuppressWarnings("restriction") public class DESUtils { private static Key key; private static String KEY_STR = "myKey"; private static String CHARSETNAME = "UTF-8"; private static String ALGORITHM = "DES"; static { try { KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(KEY_STR.getBytes()); generator.init(secureRandom); key = generator.generateKey(); generator = null; } catch (Exception e) { throw new RuntimeException(e); } } public static String encrypt(String str) { BASE64Encoder base64encoder = new BASE64Encoder(); try { byte[] bytes = str.getBytes(CHARSETNAME); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] doFinal = cipher.doFinal(bytes); return base64encoder.encode(doFinal); } catch (Exception e) { throw new RuntimeException(e); } } public static String decrypt(String str) { BASE64Decoder base64decoder = new BASE64Decoder(); try { byte[] bytes = base64decoder.decodeBuffer(str); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); byte[] doFinal = cipher.doFinal(bytes); return new String(doFinal, CHARSETNAME); } catch (Exception e) { throw new RuntimeException(e); } } }
- 使用上面的类加密自己的账户和密码,并把结果填写到配置文件中
- 编写配置类
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer { private String[] encryptPropNames = { "jdbc.username", "jdbc.password" }; @Override protected String convertProperty(String propertyName, String propertyValue) { if (isEncrypted(propertyName)) { String decryptValue = DESUtil.decrypt(propertyValue); return decryptValue; } else { return propertyValue; } } private boolean isEncrypted(String propertyName) { for (String encryptpropertyName : encryptPropNames) { if (encryptpropertyName.equals(propertyName)) { return true; } } return false; } }
- 使用上面编写的类替换
context:property-placeholder
<bean class="org.sherekr.dfo.core.util.EncryptPropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> <property name="fileEncoding" value="UTF-8" /> </bean>
- 完成编写,启动测试