之前有人问过 hibernate 密码问题,大家都没有给出一个具体的解决方案,所以我就看了一
下代码,把我的想法和实现拿出来和大家讨论一下。我现在的环境是 spring+hibernate,但
是这并不影响这个加密解密的问题,其他环境应该是略有不同,但是思路肯定是一样的。
总体思路:在工程的配置文件中填写数据库密码的密文,在应用程序使用 datasource 的时
候解密成明文以创建连接。
步骤 1
使用 java 的中 cipher 类并使用 DES(对称加密算法)算法对明文进行加密
````````````````这里如何使用 cipher 类和 DES 算法的原理可以上网查找,我懒得写了,如果大
家真的也怕麻烦自己去找的话我再写一个贴出来吧
1public class DESUtil ...{
2
3 public static void main(String[] args)...{
4 try ...{
5 if(args[0].equals("-genKey"))...{
6 generateKey(args[1]);
7 }else...{
8
9 //if (args[0].equals("-encrypt"))encrypt();
10
11 //else decrypt();
12 }
13 }catch (Exception e) ...{
14 // TODO: handle exception
15 }
16 }
17
18 public static String encrypt(String plainText, String encryptString, File keyFile)throws
IOException, ClassNotFoundException,GeneralSecurityException...{
19 ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(keyFile));
20 int mode = Cipher.ENCRYPT_MODE;
21 Key key = (Key)keyIn.readObject();
22 keyIn.close();
23
24 InputStream in = new FileInputStream(plainText);
25 OutputStream out = new FileOutputStream(encryptString);
26
27 Cipher cipher = Cipher.getInstance("DES");
28 cipher.init(mode, key);
评论0