/android/src/main/java/com/jlcool/aliossflutter/SecretUtils.java

https://github.com/jlcool/aliossflutter · Java · 89 lines · 50 code · 11 blank · 28 comment · 1 complexity · 3d9811a6ed7efbae5f2dbdda06024d4e MD5 · raw file

  1. package com.jlcool.aliossflutter;
  2. import android.util.Base64;
  3. import java.io.UnsupportedEncodingException;
  4. import javax.crypto.Cipher;
  5. import javax.crypto.SecretKey;
  6. import javax.crypto.spec.SecretKeySpec;
  7. /**
  8. * SecretUtils {3DES加密解密的工具类 }
  9. * @author William
  10. * @date 2013-04-19
  11. */
  12. public class SecretUtils {
  13. //定义加密算法,有DES、DESede(即3DES)、Blowfish
  14. private static final String Algorithm = "DESede";
  15. static String PASSWORD_CRYPT_KEY = "";
  16. /**
  17. * 加密方法
  18. * @param src 源数据的字节数组
  19. * @return
  20. */
  21. public static byte[] encryptMode(String src) {
  22. try {
  23. SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm); //生成密钥
  24. Cipher c1 = Cipher.getInstance(Algorithm); //实例化负责加密/解密的Cipher工具类
  25. c1.init(Cipher.ENCRYPT_MODE, deskey); //初始化为加密模式
  26. return Base64.encode(c1.doFinal(src.getBytes("UTF-8")),Base64.DEFAULT);
  27. } catch (java.security.NoSuchAlgorithmException e1) {
  28. e1.printStackTrace();
  29. } catch (javax.crypto.NoSuchPaddingException e2) {
  30. e2.printStackTrace();
  31. } catch (Exception e3) {
  32. e3.printStackTrace();
  33. }
  34. return null;
  35. }
  36. /**
  37. * 解密函数
  38. * @param src 密文的字节数组
  39. * @return
  40. */
  41. public static byte[] decryptMode(String src) {
  42. try {
  43. SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);
  44. Cipher c1 = Cipher.getInstance(Algorithm);
  45. c1.init(Cipher.DECRYPT_MODE, deskey); //初始化为解密模式
  46. return c1.doFinal(Base64.decode(src.getBytes("UTF-8"), Base64.DEFAULT) );
  47. } catch (java.security.NoSuchAlgorithmException e1) {
  48. e1.printStackTrace();
  49. } catch (javax.crypto.NoSuchPaddingException e2) {
  50. e2.printStackTrace();
  51. } catch (Exception e3) {
  52. e3.printStackTrace();
  53. }
  54. return null;
  55. }
  56. /*
  57. * 根据字符串生成密钥字节数组
  58. * @param keyStr 密钥字符串
  59. * @return
  60. * @throws UnsupportedEncodingException
  61. */
  62. public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException{
  63. byte[] key = new byte[24]; //声明一个24位的字节数组,默认里面都是0
  64. byte[] temp = keyStr.getBytes("UTF-8"); //将字符串转成字节数组
  65. /*
  66. * 执行数组拷贝
  67. * System.arraycopy(源数组,从源数组哪里开始拷贝,目标数组,拷贝多少位)
  68. */
  69. if(key.length > temp.length){
  70. //如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中
  71. System.arraycopy(temp, 0, key, 0, temp.length);
  72. }else{
  73. //如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中
  74. System.arraycopy(temp, 0, key, 0, key.length);
  75. }
  76. return key;
  77. }
  78. }