DES加密数据库账号密码
实现对连接数据库账号密码的加密
DESUtil:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| @SuppressWarnings("restriction") public class DESUtil { private static Key key;
private static String KEY_ETR="mykey"; private static String CHARSETNAME="utf-8"; private static String ALGORITHM="DES"; private static String OFWAY="SHA1PRNG"; static{ try { KeyGenerator generator=KeyGenerator.getInstance(ALGORITHM); SecureRandom secureRandom=SecureRandom.getInstance(OFWAY); secureRandom.setSeed(KEY_ETR.getBytes()); generator.init(secureRandom); key=generator.generateKey(); generator=null; } catch (Exception e) { e.printStackTrace(); } }
public static String getEncryptString(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 getDecryptString(String str){ BASE64Decoder base64Decoder=new BASE64Decoder(); try{ byte[] decodeBuffer = base64Decoder.decodeBuffer(str); Cipher cipher=Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); byte[] doFinal = cipher.doFinal(decodeBuffer); return new String(doFinal, CHARSETNAME); }catch(Exception e){ throw new RuntimeException(e); } finally { } } public static void main(String args[]){ String encryptString1 = getEncryptString("root"); String encryptString2 = getEncryptString("123456"); System.out.println(encryptString1); System.out.println(encryptString2); }
}
|
EncryptPropertyPlaceholderConfigurer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
private String encryptPropertyNames[]={"jdbc.username","jdbc.password"};
@Override protected String convertProperty(String propertyName, String propertyValue) { if(isEncryptProp(propertyName)){ propertyValue=DESUtil.getDecryptString(propertyValue); return propertyValue; }else{ return propertyValue; } }
private boolean isEncryptProp(String propertyName) { for (String encryptPropertyName : encryptPropertyNames) { if(encryptPropertyName.equals(propertyName)){ return true; } } return false; } }
|