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 plaincopy
  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. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章