ITeye博客

DES 加密

absolute · 2007-09-20 14:59 · Java记事本 · Markdown

java 代码

  1. public class CryptoUtils {
  2. private static final String KEY = "12345678123456781234567811111111";
  3. public static String encrypt(String strDataToEncrypt) {
  4. byte[] key = KEY.getBytes();
  5. Provider sunJCE = new com.sun.crypto.provider.SunJCE();
  6. Security.addProvider(sunJCE);
  7. String strAlgorithm = "DES";
  8. SecretKeySpec keySpec = null;
  9. 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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。