Java加密和解密

转自:http://blog.csdn.net/xiadaoceshen/article/details/8464476

概述:

出于安全考虑,网络的传输中经常对传输数据做加密和编码处理,其中涉及以下几种: 

1、md5加密,该加密算法是单向加密,即加密的数据不能再通过解密还原。相关类包含在java.security.MessageDigest包中。 

2、3-DES加密,该加密算法是可逆的,解密方可以通过与加密方约定的密钥匙进行解密。相关类包含在javax.crypto.*包中。 

3、base64编码,是用于传输8bit字节代码最常用的编码方式。相关类在sun.misc.BASE64Decoder 和sun.misc.BASE64Encoder 中。 

4、URLEncoder编码,是一种字符编码,保证被传送的参数由遵循规范的文本组成。相关类在java.net.URLEncoder包中。 

细节:
[java]  view plain copy
  1. 1、进行MD5加密,得到byte[]
  2. /**
  3. * 进行MD5加密
  4. * @param String 原始的SPKEY
  5. * @return byte[] 指定加密方式为md5后的byte[]
  6. */
  7. private byte[] md5(String strSrc)
  8. {
  9. byte[] returnByte = null;
  10. try
  11. {
  12. MessageDigest md5 = MessageDigest.getInstance("MD5");
  13. returnByte = md5.digest(strSrc.getBytes("GBK"));
  14. }
  15. catch(Exception e)
  16. {
  17. e.printStackTrace();
  18. }
  19. return returnByte;
  20. }
  21. 2、得到3-DES的密钥匙
  22. /**
  23. * 得到3-DES的密钥匙
  24. * 根据根据需要,如密钥匙为24个字节,md5加密出来的是16个字节,因此后面补8个字节的0
  25. * @param String 原始的SPKEY
  26. * @return byte[] 指定加密方式为md5后的byte[]
  27. */
  28. private byte[] getEnKey(String spKey)
  29. {
  30. byte[] desKey=null;
  31. try
  32. {
  33. byte[] desKey1 = md5(spKey);
  34. desKey = new byte[24];
  35. int i = 0;
  36. while (i < desKey1.length && i < 24) {
  37. desKey[i] = desKey1[i];
  38. i++;
  39. }
  40. if (i < 24) {
  41. desKey[i] = 0;
  42. i++;
  43. }
  44. }
  45. catch(Exception e){
  46. e.printStackTrace();
  47. }
  48. return desKey;
  49. }
  50. 33-DES加密
  51. /**
  52. * 3-DES加密
  53. * @param byte[] src 要进行3-DES加密的byte[]
  54. * @param byte[] enKey 3-DES加密密钥
  55. * @return byte[] 3-DES加密后的byte[]
  56. */
  57. public byte[] Encrypt(byte[] src,byte[] enKey)
  58. {
  59. byte[] encryptedData = null;
  60. try
  61. {
  62. DESedeKeySpec dks = new DESedeKeySpec(enKey);
  63. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
  64. SecretKey key = keyFactory.generateSecret(dks);
  65. Cipher cipher = Cipher.getInstance("DESede");
  66. cipher.init(Cipher.ENCRYPT_MODE, key);
  67. encryptedData = cipher.doFinal(src);
  68. }
  69. catch(Exception e)
  70. {
  71. e.printStackTrace();
  72. }
  73. return encryptedData;
  74. }
  75. 4、对字符串进行Base64编码
  76. /**
  77. * 对字符串进行Base64编码
  78. * @param byte[] src 要进行编码的字符
  79. *
  80. * @return String 进行编码后的字符串
  81. */
  82. public String getBase64Encode(byte[] src)
  83. {
  84. String requestValue="";
  85. try{
  86. BASE64Encoder base64en = new BASE64Encoder();
  87. requestValue=base64en.encode(src);
  88. //System.out.println(requestValue);
  89. }
  90. catch(Exception e){
  91. e.printStackTrace();
  92. }
  93. return requestValue;
  94. }
  95. 5、根据需要可以去掉字符串的换行符号
  96. /**
  97. * 去掉字符串的换行符号
  98. * base64编码3-DES的数据时,得到的字符串有换行符号,根据需要可以去掉
  99. */
  100. private String filter(String str)
  101. {
  102. String output = null;
  103. StringBuffer sb = new StringBuffer();
  104. for(int i = 0; i < str.length(); i++)
  105. {
  106. int asc = str.charAt(i);
  107. if(asc != 10 && asc != 13)
  108. sb.append(str.subSequence(i, i + 1));
  109. }
  110. output = new String(sb);
  111. return output;
  112. }
  113. 6、对字符串进行URLDecoder.encode(strEncoding)编码
  114. /**
  115. * 对字符串进行URLDecoder.encode(strEncoding)编码
  116. * @param String src 要进行编码的字符串
  117. *
  118. * @return String 进行编码后的字符串
  119. */
  120. public String getURLEncode(String src)
  121. {
  122. String requestValue="";
  123. try{
  124. requestValue = URLEncoder.encode(src);
  125. }
  126. catch(Exception e){
  127. e.printStackTrace();
  128. }
  129. return requestValue;
  130. }
  131. 7、对字符串进行URLDecoder.decode(strEncoding)解码
  132. /**
  133. * 对字符串进行URLDecoder.decode(strEncoding)解码
  134. * @param String src 要进行解码的字符串
  135. *
  136. * @return String 进行解码后的字符串
  137. */
  138. public String getURLDecoderdecode(String src)
  139. {
  140. String requestValue="";
  141. try{
  142. requestValue = URLDecoder.decode(src);
  143. }
  144. catch(Exception e){
  145. e.printStackTrace();
  146. }
  147. return requestValue;
  148. }
  149. 8、进行3-DES解密(密钥匙等同于加密的密钥匙)
  150. /**
  151. *
  152. *进行3-DES解密(密钥匙等同于加密的密钥匙)。
  153. * @param byte[] src 要进行3-DES解密byte[]
  154. * @param String spkey分配的SPKEY
  155. * @return String 3-DES解密后的String
  156. */
  157. public String deCrypt(byte[] debase64,String spKey)
  158. {
  159. String strDe = null;
  160. Cipher cipher = null;
  161. try
  162. {
  163. cipher=Cipher.getInstance("DESede");
  164. byte[] key = getEnKey(spKey);
  165. DESedeKeySpec dks = new DESedeKeySpec(key);
  166. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
  167. SecretKey sKey = keyFactory.generateSecret(dks);
  168. cipher.init(Cipher.DECRYPT_MODE, sKey);
  169. byte ciphertext[] = cipher.doFinal(debase64);
  170. strDe = new String(ciphertext,"UTF-16LE");
  171. }
  172. catch(Exception ex)
  173. {
  174. strDe = "";
  175. ex.printStackTrace();
  176. }
  177. return strDe;
  178. 经过以上步骤就可以完成MD5加密,3-DES加密、base64编码传输、base64解码、3-DES解密得到原文。
  179. 程序全文如下:
  180. package com.neusoft.test.util.crypt;
  181. import java.io.IOException;
  182. import java.io.UnsupportedEncodingException;
  183. import java.net.URLDecoder;
  184. import java.net.URLEncoder;
  185. import java.security.MessageDigest;
  186. import java.text.SimpleDateFormat;
  187. import java.util.Calendar;
  188. import javax.crypto.Cipher;
  189. import javax.crypto.SecretKey;
  190. import javax.crypto.SecretKeyFactory;
  191. import javax.crypto.spec.DESedeKeySpec;
  192. import sun.misc.BASE64Decoder;
  193. import sun.misc.BASE64Encoder;
  194. /**
  195. * <p>Title:加密解密测试</p>
  196. *
  197. * <p>Description: 加密解密</p>
  198. *
  199. *<p>Date : 2005-08-11</p>
  200. *
  201. * <p>Copyright: Copyright (c) 2005 neusoft</p>
  202. *
  203. * <p>Company: neusoft</p>
  204. *
  205. * @author mengk
  206. * @version 1.00
  207. *
  208. * <p>------------------------------------------------------------</p>
  209. * <p> 修改历史 </p>
  210. * <p> 序号 日期 修改人 修改原因</p>
  211. * <p> 1 </p>
  212. */
  213. public class Endecrypt {
  214. /**
  215. * 进行MD5加密
  216. * @param String 原始的SPKEY
  217. * @return byte[] 指定加密方式为md5后的byte[]
  218. */
  219. private byte[] md5(String strSrc)
  220. {
  221. byte[] returnByte = null;
  222. try
  223. {
  224. MessageDigest md5 = MessageDigest.getInstance("MD5");
  225. returnByte = md5.digest(strSrc.getBytes("GBK"));
  226. }
  227. catch(Exception e)
  228. {
  229. e.printStackTrace();
  230. }
  231. return returnByte;
  232. }
  233. /**
  234. * 得到3-DES的密钥匙
  235. * 根据接口规范,密钥匙为24个字节,md5加密出来的是16个字节,因此后面补8个字节的0
  236. * @param String 原始的SPKEY
  237. * @return byte[] 指定加密方式为md5后的byte[]
  238. */
  239. private byte[] getEnKey(String spKey)
  240. {
  241. byte[] desKey=null;
  242. try
  243. {
  244. byte[] desKey1 = md5(spKey);
  245. desKey = new byte[24];
  246. int i = 0;
  247. while (i < desKey1.length && i < 24) {
  248. desKey[i] = desKey1[i];
  249. i++;
  250. }
  251. if (i < 24) {
  252. desKey[i] = 0;
  253. i++;
  254. }
  255. }
  256. catch(Exception e){
  257. e.printStackTrace();
  258. }
  259. return desKey;
  260. }
  261. /**
  262. * 3-DES加密
  263. * @param byte[] src 要进行3-DES加密的byte[]
  264. * @param byte[] enKey 3-DES加密密钥
  265. * @return byte[] 3-DES加密后的byte[]
  266. */
  267. public byte[] Encrypt(byte[] src,byte[] enKey)
  268. {
  269. byte[] encryptedData = null;
  270. try
  271. {
  272. DESedeKeySpec dks = new DESedeKeySpec(enKey);
  273. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
  274. SecretKey key = keyFactory.generateSecret(dks);
  275. Cipher cipher = Cipher.getInstance("DESede");
  276. cipher.init(Cipher.ENCRYPT_MODE, key);
  277. encryptedData = cipher.doFinal(src);
  278. }
  279. catch(Exception e)
  280. {
  281. e.printStackTrace();
  282. }
  283. return encryptedData;
  284. }
  285. /**
  286. * 对字符串进行Base64编码
  287. * @param byte[] src 要进行编码的字符
  288. *
  289. * @return String 进行编码后的字符串
  290. */
  291. public String getBase64Encode(byte[] src)
  292. {
  293. String requestValue="";
  294. try{
  295. BASE64Encoder base64en = new BASE64Encoder();
  296. requestValue=base64en.encode(src);
  297. //System.out.println(requestValue);
  298. }
  299. catch(Exception e){
  300. e.printStackTrace();
  301. }
  302. return requestValue;
  303. }
  304. /**
  305. * 去掉字符串的换行符号
  306. * base64编码3-DES的数据时,得到的字符串有换行符号
  307. * ,一定要去掉,否则uni-wise平台解析票根不会成功,
  308. * 提示“sp验证失败”。在开发的过程中,因为这个问题让我束手无策,
  309. * 一个朋友告诉我可以问联通要一段加密后 的文字,然后去和自己生成的字符串比较,
  310. * 这是个不错的调试方法。我最后比较发现我生成的字符串唯一不同的 是多了换行。
  311. * 我用c#语言也写了票根请求程序,没有发现这个问题。
  312. *
  313. */
  314. private String filter(String str)
  315. {
  316. String output = null;
  317. StringBuffer sb = new StringBuffer();
  318. for(int i = 0; i < str.length(); i++)
  319. {
  320. int asc = str.charAt(i);
  321. if(asc != 10 && asc != 13)
  322. sb.append(str.subSequence(i, i + 1));
  323. }
  324. output = new String(sb);
  325. return output;
  326. }
  327. /**
  328. * 对字符串进行URLDecoder.encode(strEncoding)编码
  329. * @param String src 要进行编码的字符串
  330. *
  331. * @return String 进行编码后的字符串
  332. */
  333. public String getURLEncode(String src)
  334. {
  335. String requestValue="";
  336. try{
  337. requestValue = URLEncoder.encode(src);
  338. }
  339. catch(Exception e){
  340. e.printStackTrace();
  341. }
  342. return requestValue;
  343. }
  344. /**
  345. * 3-DES加密
  346. * @param String src 要进行3-DES加密的String
  347. * @param String spkey分配的SPKEY
  348. * @return String 3-DES加密后的String
  349. */
  350. public String get3DESEncrypt(String src,String spkey)
  351. {
  352. String requestValue="";
  353. try{
  354. //得到3-DES的密钥匙
  355. byte[] enKey = getEnKey(spkey);
  356. //要进行3-DES加密的内容在进行/"UTF-16LE/"取字节
  357. byte[] src2 = src.getBytes("UTF-16LE");
  358. //进行3-DES加密后的内容的字节
  359. byte[] encryptedData = Encrypt(src2,enKey);
  360. //进行3-DES加密后的内容进行BASE64编码
  361. String base64String = getBase64Encode(encryptedData);
  362. //BASE64编码去除换行符后
  363. String base64Encrypt = filter(base64String);
  364. //对BASE64编码中的HTML控制码进行转义的过程
  365. requestValue=getURLEncode(base64Encrypt);
  366. //System.out.println(requestValue);
  367. }
  368. catch(Exception e){
  369. e.printStackTrace();
  370. }
  371. return requestValue;
  372. }
  373. /**
  374. * 对字符串进行URLDecoder.decode(strEncoding)解码
  375. * @param String src 要进行解码的字符串
  376. *
  377. * @return String 进行解码后的字符串
  378. */
  379. public String getURLDecoderdecode(String src)
  380. {
  381. String requestValue="";
  382. try{
  383. requestValue = URLDecoder.decode(src);
  384. }
  385. catch(Exception e){
  386. e.printStackTrace();
  387. }
  388. return requestValue;
  389. }
  390. /**
  391. *
  392. *进行3-DES解密(密钥匙等同于加密的密钥匙)。
  393. * @param byte[] src 要进行3-DES解密byte[]
  394. * @param String spkey分配的SPKEY
  395. * @return String 3-DES解密后的String
  396. */
  397. public String deCrypt(byte[] debase64,String spKey)
  398. {
  399. String strDe = null;
  400. Cipher cipher = null;
  401. try
  402. {
  403. cipher=Cipher.getInstance("DESede");
  404. byte[] key = getEnKey(spKey);
  405. DESedeKeySpec dks = new DESedeKeySpec(key);
  406. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
  407. SecretKey sKey = keyFactory.generateSecret(dks);
  408. cipher.init(Cipher.DECRYPT_MODE, sKey);
  409. byte ciphertext[] = cipher.doFinal(debase64);
  410. strDe = new String(ciphertext,"UTF-16LE");
  411. }
  412. catch(Exception ex)
  413. {
  414. strDe = "";
  415. ex.printStackTrace();
  416. }
  417. return strDe;
  418. }
  419. /**
  420. * 3-DES解密
  421. * @param String src 要进行3-DES解密的String
  422. * @param String spkey分配的SPKEY
  423. * @return String 3-DES加密后的String
  424. */
  425. public String get3DESDecrypt(String src,String spkey)
  426. {
  427. String requestValue="";
  428. try{
  429. //得到3-DES的密钥匙
  430. //URLDecoder.decodeTML控制码进行转义的过程
  431. String URLValue=getURLDecoderdecode(src);
  432. //进行3-DES加密后的内容进行BASE64编码
  433. BASE64Decoder base64Decode = new BASE64Decoder();
  434. byte[] base64DValue = base64Decode.decodeBuffer(URLValue);
  435. //要进行3-DES加密的内容在进行/"UTF-16LE/"取字节
  436. requestValue = deCrypt(base64DValue,spkey);
  437. }
  438. catch(Exception e){
  439. e.printStackTrace();
  440. }
  441. return requestValue;
  442. }
  443. public static void main(String[] args) {
  444. Endecrypt test = new Endecrypt();
  445. String oldString = "毒素发";
  446. String SPKEY = "1234";
  447. System.out.println("1。分配的SPKEY为: "+SPKEY);
  448. System.out.println("2。的内容为: "+oldString);
  449. String reValue = test.get3DESEncrypt(oldString,SPKEY);
  450. reValue = reValue.trim().intern();
  451. System.out.println("进行3-DES加密后的内容: "+reValue);
  452. String reValue2 = test.get3DESDecrypt(reValue,SPKEY);
  453. System.out.println("进行3-DES解密后的内容: "+reValue2);
  454. }
  455. }

猜你喜欢

转载自blog.csdn.net/maco_liao/article/details/51010546