/src/main/java/com/u8/server/sdk/quanmingzhushou/ThreeDesUtil.java

https://github.com/uustory/U8Server · Java · 84 lines · 30 code · 13 blank · 41 comment · 0 complexity · c66d42f71153b0d4ffe96ec29e6ce32e MD5 · raw file

  1. package com.u8.server.sdk.quanmingzhushou;
  2. import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.SecretKey;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import java.security.Security;
  7. /**
  8. * author Administrator on 2015-09-21.
  9. */
  10. public class ThreeDesUtil {
  11. static {
  12. //添加新安全算法,如果用JCE就要把它添加进去
  13. Security.addProvider(new com.sun.crypto.provider.SunJCE());
  14. }
  15. /**
  16. * args在java中调用sun公司提供的3DES加密解密算法时,需要使
  17. * 用到$JAVA_HOME/jre/lib/目录下如下的4个jar包:
  18. * jce.jar
  19. * security/US_export_policy.jar
  20. * security/local_policy.jar
  21. * ext/sunjce_provider.jar
  22. */
  23. private static final String Algorithm = "DESede"; //定义加密算法,可用 DES,DESede,Blowfish
  24. //keybyte为加密密钥,长度为24字节
  25. //src为被加密的数据缓冲区(源)
  26. private static byte[] encryptMode(byte[] keybyte, byte[] src) throws Exception {
  27. //生成密钥
  28. SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
  29. //加密
  30. Cipher c1 = Cipher.getInstance(Algorithm);
  31. c1.init(Cipher.ENCRYPT_MODE, deskey);
  32. return c1.doFinal(src);//在单一方面的加密或解密
  33. }
  34. //keybyte为加密密钥,长度为24字节
  35. //src为加密后的缓冲区
  36. private static byte[] decryptMode(byte[] keybyte, byte[] src) throws Exception {
  37. //生成密钥
  38. SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
  39. //解密
  40. Cipher c1 = Cipher.getInstance(Algorithm);
  41. c1.init(Cipher.DECRYPT_MODE, deskey);
  42. return c1.doFinal(src);
  43. }
  44. // private static byte[] hex(String str) throws Exception {
  45. // String f = MD5Util.getMD5HexString(str);
  46. // byte[] bkeys = f.getBytes();
  47. // byte[] enk = new byte[24];
  48. // System.arraycopy(bkeys, 0, enk, 0, 24);
  49. // return enk;
  50. // }
  51. /**
  52. * 加密数据
  53. *
  54. * @param key 秘钥
  55. * @param str 需要加密内容
  56. * @return 加密后的数据
  57. */
  58. public static String thressDesEncrypt(String key, String str) throws Exception {
  59. return Base64.encode(encryptMode(key.getBytes(), str.getBytes()));
  60. }
  61. /**
  62. * 解密数据
  63. *
  64. * @param key 秘钥
  65. * @param str 需要解密内容
  66. * @return 解密后的数据
  67. */
  68. public static String thressDesDecrypt(String key, String str) throws Exception {
  69. return new String(decryptMode(key.getBytes(), Base64.decode(str)));
  70. }
  71. }