---
title: "随机加密方法"
author: "zwfc"
date: "2008-11-14T12:01:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-11-14T12:01:00Z"
id: 470950
url: "https://zwfc.iteye.com/blog/470950"
---

01. importjava.security.MessageDigest;
02. importjava.security.NoSuchAlgorithmException;
03. importjava.util.Random;
04. importjavax.crypto.Cipher;
05. importjavax.crypto.SecretKey;
06. importjavax.crypto.SecretKeyFactory;
07. importjavax.crypto.spec.PBEKeySpec;
08. importjavax.crypto.spec.PBEParameterSpec;
09. publicclassSecurityUtil{
10. char\[]passwd="mykey".toCharArray();
11. byte\[]salt;
12. //加密，即使明文一样每次加密的密文都不一样。
13. publicbyte\[]encrypt(Stringtext)throwsException{
14. //
15. PBEKeySpecpbks=newPBEKeySpec(passwd);
16. //由口令生成密钥
17. SecretKeyFactorykf=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
18. SecretKeyk=kf.generateSecret(pbks);
19. //生成随机数盐
20. salt=newbyte\[8];
21. Randomr=newRandom();
22. r.nextBytes(salt);
23. //创建并初始化密码器
24. Ciphercp=Cipher.getInstance("PBEWithMD5AndDES");
25. PBEParameterSpecps=newPBEParameterSpec(salt,1000);
26. cp.init(Cipher.ENCRYPT\_MODE,k,ps);
27. //获取明文，执行加密
28. byte\[]ptext=text.getBytes();
29. returncp.doFinal(ptext);
30. }
31. //解密
32. publicStringdecrypt(byte\[]ctext,byte\[]salt)throwsException{
33. //
34. PBEKeySpecpbks=newPBEKeySpec(passwd);
35. //由口令生成密钥
36. SecretKeyFactorykf=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
37. SecretKeyk=kf.generateSecret(pbks);
38. //创建并初始化密码器
39. Ciphercp=Cipher.getInstance("PBEWithMD5AndDES");
40. PBEParameterSpecps=newPBEParameterSpec(salt,1000);
41. cp.init(Cipher.DECRYPT\_MODE,k,ps);
42. byte\[]ptext=cp.doFinal(ctext);
43. returnnewString(ptext);
44. }
45. /\**
46. \*@returnReturnsthesalt.
47. \*/
48. publicbyte\[]getSalt(){
49. returnsalt;
50. }
51. //MD5加密，每次加密都是固定的。
52. publicStringMD5(StringplainText)throwsNoSuchAlgorithmException{
53. MessageDigestmd=MessageDigest.getInstance("MD5");
54. md.update(plainText.getBytes());
55. byteb\[]=md.digest();
56. inti;
57. StringBufferbuf=newStringBuffer("");
58. for(intoffset=0;offset&lt;b.length;offset++){
59. i=b\[offset];
60. if(i&lt;0)
61. i+=256;
62. if(i&lt;16)
63. buf.append("0");
64. buf.append(Integer.toHexString(i));
65. }
66. returnbuf.toString();//32位的加密
67. }
68. }