---
title: "DES 加密"
author: "absolute"
date: "2007-09-20T14:59:00Z"
tags: []
slug: "des"
draft: false
lastmod: "2007-09-20T14:59:00Z"
id: 125650
url: "https://absolute.iteye.com/blog/125650"
---

java 代码

01. public class CryptoUtils {
02. private static final String KEY = "12345678123456781234567811111111";
03. public static String encrypt(String strDataToEncrypt) {
04. byte\[] key = KEY.getBytes();
05. Provider sunJCE = new com.sun.crypto.provider.SunJCE();
06. Security.addProvider(sunJCE);
07. String strAlgorithm = "DES";
08. SecretKeySpec keySpec = null;
09. DESKeySpec deskey = null;
10. String strResult = "";
11. try {
12. deskey = new DESKeySpec(key);
13. keySpec = new SecretKeySpec(deskey.getKey(), "DES");
14. Cipher cipher = Cipher.getInstance(strAlgorithm);
15. cipher.init(Cipher.ENCRYPT\_MODE, keySpec);
16. byte\[] utf8 = strDataToEncrypt.getBytes("UTF8");
17. byte\[] enc = cipher.doFinal(utf8);
18. strResult = new sun.misc.BASE64Encoder().encode(enc);
19. } catch (Exception e) {
20. e.printStackTrace();
21. }
22. return strResult;
23. }
24. /\**
25. * This function decrypt a given string using the DES algorithm.
26. * @param strDataToDecrypt The String to decrypt
27. * @param strKey The generated key used to decrypt
28. * @return The encrypted string
29. \*/
30. public static String decrypt(String strDataToDecrypt) {
31. byte\[] key = KEY.getBytes();
32. Provider sunJCE = new com.sun.crypto.provider.SunJCE();
33. Security.addProvider(sunJCE);
34. String strAlgorithm = "DES";
35. SecretKeySpec keySpec = null;
36. DESKeySpec deskey = null;
37. String strResult = "";
38. try {
39. deskey = new DESKeySpec(key);
40. keySpec = new SecretKeySpec(deskey.getKey(), "DES");
41. Cipher cipher = Cipher.getInstance(strAlgorithm);
42. cipher.init(Cipher.DECRYPT\_MODE, keySpec);
43. byte\[] dec = new sun.misc.BASE64Decoder().decodeBuffer(strDataToDecrypt);
44. byte\[] utf8 = cipher.doFinal(dec);
45. return new String(utf8, "UTF8");
46. }
47. catch (Exception e) {
48. e.printStackTrace();
49. }
50. return strResult;
51. }
52. }