android加密DESede/CBC/PKCS5Padding

来源:互联网 发布:双人無心内事无人知 编辑:程序博客网 时间:2024/05/01 10:29
工作中需要和HPH对接,接口一些敏感信息,讨论后用3DES加密,由于我做的android邮件客户端是依附于php系统,所以我写加密算法对接HPH的加密,然后遇到一个棘手的问题,我的加密解密过程顺利,但是同样的密钥,同样的明文,java和php加密不一样,后来发现双方理解有误我理解的密钥是byte[]类型的,对方的密钥是通过类似String.getBytes()的方法出来的

9.jpg (3.22 KB, 下载次数: 0)

下载附件  保存到相册

5 小时前 上传

引此为戒
  1. import java.security.SecureRandom;
  2. import java.security.Security;
  3. import java.util.Random;

  4. import javax.crypto.Cipher;
  5. import javax.crypto.KeyGenerator;
  6. import javax.crypto.SecretKey;
  7. import javax.crypto.SecretKeyFactory;
  8. import javax.crypto.spec.DESedeKeySpec;
  9. import javax.crypto.spec.IvParameterSpec;
  10. import javax.crypto.spec.SecretKeySpec;

  11. /*字符串 DESede(3DES) 加密*/

  12. public class ThreeDes {

  13.     /**
  14.      * 3DS加密
  15.      *
  16.      * @author liyunlong_88@126.com
  17.      */

  18.     private static final String Algorithm = "DESede/CBC/PKCS5Padding"; // 定义加密算法,可用
  19.                                                                         // DES,DESede,Blowfish,DESede/CBC/PKCS5Padding

  20.     // keybyte为加密密钥,长度为24字节

  21.     // src为被加密的数据缓冲区(源)
  22.     /*
  23.      * private static SecretKey deskey = null;
  24.      *
  25.      * public static void getKey(byte[] strKey) { try { KeyGenerator _generator
  26.      * = KeyGenerator.getInstance("DES"); _generator.init(new
  27.      * SecureRandom(strKey)); deskey = _generator.generateKey(); _generator =
  28.      * null; } catch (Exception e) { e.printStackTrace(); } }
  29.      */
  30.     public static byte[] encryptMode(String iv, String key, String src) {

  31.         try {
  32.             byte[] keybyte = key.getBytes();
  33.             byte[] rand = new byte[8];
  34.             rand = iv.getBytes();
  35.             // 用随即数生成初始向量

  36.             /*
  37.              * Random r=new Random(); r.nextBytes(rand);
  38.              */
  39.             IvParameterSpec ivp = new IvParameterSpec(rand);

  40.             // 生成密钥

  41.            // SecureRandom sr = new SecureRandom();
  42.             DESedeKeySpec dks = new DESedeKeySpec(keybyte);
  43.             SecretKeyFactory keyFactory = SecretKeyFactory
  44.                     .getInstance("DESede");
  45.             SecretKey securekey = keyFactory.generateSecret(dks);
  46.             // IvParameterSpec iv = new IvParameterSpec(PASSWORD_IV.getBytes());
  47.             /*
  48.              * Cipher cipher = Cipher.getInstance("DESede");
  49.              * cipher.init(Cipher.ENCRYPT_MODE, securekey, ivp, sr); return new
  50.              * String(Hex.encodeHex(cipher.doFinal(str.getBytes())));
  51.              */

  52.             // 加密

  53.             Cipher c1 = Cipher.getInstance(Algorithm);

  54.             c1.init(Cipher.ENCRYPT_MODE, securekey, ivp);

  55.             return c1.doFinal(src.getBytes());// 在单一方面的加密或解密

  56.         } catch (java.security.NoSuchAlgorithmException e1) {

  57.             // TODO: handle exception

  58.             e1.printStackTrace();

  59.         } catch (javax.crypto.NoSuchPaddingException e2) {

  60.             e2.printStackTrace();

  61.         } catch (java.lang.Exception e3) {

  62.             e3.printStackTrace();

  63.         }

  64.         return null;

  65.     }

  66.     // keybyte为加密密钥,长度为24字节

  67.     // src为加密后的缓冲区

  68.     public static byte[] decryptMode(String iv, String key, byte[] src) {

  69.         try {
  70.             byte[] srcbytes = src;
  71.             byte[] keybyte = key.getBytes();
  72.             byte[] rand = new byte[8];
  73.             rand = iv.getBytes();
  74.             // 用随即数生成初始向量

  75.             /*
  76.              * Random r=new Random(); r.nextBytes(rand);
  77.              */
  78.             IvParameterSpec ivp = new IvParameterSpec(rand);

  79.             // 生成密钥

  80.             SecureRandom sr = new SecureRandom();
  81.             DESedeKeySpec dks = new DESedeKeySpec(keybyte);
  82.             SecretKeyFactory keyFactory = SecretKeyFactory
  83.                     .getInstance("DESede");
  84.             SecretKey securekey = keyFactory.generateSecret(dks);

  85.             // 解密

  86.             Cipher c1 = Cipher.getInstance(Algorithm);

  87.             c1.init(Cipher.DECRYPT_MODE, securekey, ivp);

  88.             /*
  89.              * int len = src.getBytes().length; byte[] zero = { 0x00, 0x00,
  90.              * 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (len < 8) { srcbytes =
  91.              * new byte[8]; System.arraycopy(src.getBytes(), 0, srcbytes, 0,
  92.              * len); System.arraycopy(zero, len, srcbytes, len, 8 - len); } else
  93.              * { srcbytes = src.getBytes(); }
  94.              */

  95.             return c1.doFinal(srcbytes);

  96.         } catch (java.security.NoSuchAlgorithmException e1) {

  97.             // TODO: handle exception

  98.             e1.printStackTrace();

  99.         } catch (javax.crypto.NoSuchPaddingException e2) {

  100.             e2.printStackTrace();

  101.         } catch (java.lang.Exception e3) {

  102.             e3.printStackTrace();

  103.         }

  104.         return null;

  105.     }

  106.     // 转换成十六进制字符串

  107.     public static String byte2Hex(byte[] b) {

  108.         String hs = "";

  109.         String stmp = "";

  110.         for (int n = 0; n < b.length; n++) {

  111.             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));

  112.             if (stmp.length() == 1) {

  113.                 hs = hs + "0" + stmp;

  114.             } else {

  115.                 hs = hs + stmp;

  116.             }

  117.             if (n < b.length - 1)
  118.                 hs = hs + ":";

  119.         }

  120.         return hs.toUpperCase();

  121.     }

  122.     public static final String encodeHex(byte bytes[]) {
  123.         StringBuffer buf = new StringBuffer(bytes.length * 2);
  124.         for (int i = 0; i < bytes.length; i++) {
  125.             if ((bytes[i] & 0xff) < 16)
  126.                 buf.append("0");
  127.             buf.append(Long.toString(bytes[i] & 0xff, 16));
  128.         }
  129.         return buf.toString();
  130.     }

  131.     public static final byte[] decodeHex(String hex) {
  132.         char chars[] = hex.toCharArray();
  133.         byte bytes[] = new byte[chars.length / 2];
  134.         int byteCount = 0;
  135.         for (int i = 0; i < chars.length; i += 2) {
  136.             int newByte = 0;
  137.             newByte |= hexCharToByte(chars[i]);
  138.             newByte <<= 4;
  139.             newByte |= hexCharToByte(chars[i + 1]);
  140.             bytes[byteCount] = (byte) newByte;
  141.             byteCount++;
  142.         }
  143.         return bytes;
  144.     }

  145.     private static final byte hexCharToByte(char ch) {
  146.         switch (ch) {
  147.         case 48: // '0'
  148.             return 0;

  149.         case 49: // '1'
  150.             return 1;

  151.         case 50: // '2'
  152.             return 2;

  153.         case 51: // '3'
  154.             return 3;

  155.         case 52: // '4'
  156.             return 4;

  157.         case 53: // '5'
  158.             return 5;

  159.         case 54: // '6'
  160.             return 6;

  161.         case 55: // '7'
  162.             return 7;

  163.         case 56: // '8'
  164.             return 8;

  165.         case 57: // '9'
  166.             return 9;

  167.         case 97: // 'a'
  168.             return 10;

  169.         case 98: // 'b'
  170.             return 11;

  171.         case 99: // 'c'
  172.             return 12;

  173.         case 100: // 'd'
  174.             return 13;

  175.         case 101: // 'e'
  176.             return 14;

  177.         case 102: // 'f'
  178.             return 15;

  179.         case 58: // ':'
  180.         case 59: // ';'
  181.         case 60: // '<'
  182.         case 61: // '='
  183.         case 62: // '>'
  184.         case 63: // '?'
  185.         case 64: // '@'
  186.         case 65: // 'A'
  187.         case 66: // 'B'
  188.         case 67: // 'C'
  189.         case 68: // 'D'
  190.         case 69: // 'E'
  191.         case 70: // 'F'
  192.         case 71: // 'G'
  193.         case 72: // 'H'
  194.         case 73: // 'I'
  195.         case 74: // 'J'
  196.         case 75: // 'K'
  197.         case 76: // 'L'
  198.         case 77: // 'M'
  199.         case 78: // 'N'
  200.         case 79: // 'O'
  201.         case 80: // 'P'
  202.         case 81: // 'Q'
  203.         case 82: // 'R'
  204.         case 83: // 'S'
  205.         case 84: // 'T'
  206.         case 85: // 'U'
  207.         case 86: // 'V'
  208.         case 87: // 'W'
  209.         case 88: // 'X'
  210.         case 89: // 'Y'
  211.         case 90: // 'Z'
  212.         case 91: // '['
  213.         case 92: // '\\'
  214.         case 93: // ']'
  215.         case 94: // '^'
  216.         case 95: // '_'
  217.         case 96: // '`'
  218.         default:
  219.             return 0;
  220.         }
  221.     }

  222.     public static void main(String[] args) {

  223.         // TODO Auto-generated method stub

  224.         // 添加新安全算法,如果用JCE就要把它添加进去

  225.         // Security.addProvider(new com.sun.crypto.provider.SunJCE());

  226.         /*
  227.          * final byte[] keyBytes = { 0x01, 0x02, 0x03, 0x04,
  228.          *
  229.          * (byte) 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x01, 0x02,
  230.          *
  231.          * (byte) 0x03,
  232.          *
  233.          * (byte) 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
  234.          *
  235.          * (byte) 0x00, 0x01, 0x02, 0x03,
  236.          *
  237.          * (byte) 0x04
  238.          *
  239.          * }; // 24字节的密钥
  240.          */
  241.         String szSrc = "1";

  242.         System.out.println("加密前的字符串:" + szSrc);

  243.         byte[] encoded = encryptMode("12345678", "123456789012345678943210",
  244.                 szSrc);

  245.         System.out.println("加密后的字符串:" + encodeHex(encoded));

  246.         byte[] srcBytes = decryptMode("12345678", "123456789012345678943210",
  247.                 "c5e8faaf1a0e52ae".getBytes());

  248.         System.out.println("解密后的字符串:" + (new String(srcBytes)));

  249.     }

  250. }
原创粉丝点击