首页 > 技术文章 > 秘钥加密解密

wdpnodecodes 2017-12-07 23:31 原文

做项目时,需要解密接口请求回来的被加密的数据,需要根据公钥进行解密

  1 package com._21cn.points.common.utils.encrypt.XXtea;
  2 
  3 import java.security.NoSuchAlgorithmException;
  4 
  5 import javax.crypto.KeyGenerator;
  6 import javax.crypto.Mac;
  7 import javax.crypto.SecretKey;
  8 import javax.crypto.spec.SecretKeySpec;
  9 import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
 10 
 11 
 12 // Referenced classes of package com._21cn.open.common.cipher:
 13 //            ByteFormat, StringUtil
 14 
 15 public class MACTool
 16 {
 17 
 18     public MACTool()
 19     {
 20     }
 21 
 22     public static byte[] initHmacMD5Key()
 23         throws NoSuchAlgorithmException
 24     {
 25         KeyGenerator generator = KeyGenerator.getInstance("HmacMD5");
 26         SecretKey secretKey = generator.generateKey();
 27         byte key[] = secretKey.getEncoded();
 28         return key;
 29     }
 30 
 31     public static String encodeHmacMD5(byte data[], byte key[])
 32         throws Exception
 33     {
 34         SecretKey secretKey = new SecretKeySpec(key, "HmacMD5");
 35         Mac mac = Mac.getInstance(secretKey.getAlgorithm());
 36         mac.init(secretKey);
 37         byte digest[] = mac.doFinal(data);
 38         return (new HexBinaryAdapter()).marshal(digest);
 39     }
 40 
 41     public static byte[] initHmacSHAKey()
 42         throws NoSuchAlgorithmException
 43     {
 44         KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
 45         SecretKey secretKey = generator.generateKey();
 46         byte key[] = secretKey.getEncoded();
 47         return key;
 48     }
 49 
 50     public static String encodeHmacSHA1(byte data[], byte key[])
 51         throws Exception
 52     {
 53         SecretKey secretKey = new SecretKeySpec(key, "HmacSHA1");
 54         Mac mac = Mac.getInstance(secretKey.getAlgorithm());
 55         mac.init(secretKey);
 56         byte digest[] = mac.doFinal(data);
 57         return (new HexBinaryAdapter()).marshal(digest);
 58     }
 59 
 60     public static byte[] initHmacSHA256Key()
 61         throws NoSuchAlgorithmException
 62     {
 63         KeyGenerator generator = KeyGenerator.getInstance("HmacSHA256");
 64         SecretKey secretKey = generator.generateKey();
 65         byte key[] = secretKey.getEncoded();
 66         return key;
 67     }
 68 
 69     public static String encodeHmacSHA256(byte data[], byte key[])
 70         throws Exception
 71     {
 72         SecretKey secretKey = new SecretKeySpec(key, "HmacSHA256");
 73         Mac mac = Mac.getInstance(secretKey.getAlgorithm());
 74         mac.init(secretKey);
 75         byte digest[] = mac.doFinal(data);
 76         return (new HexBinaryAdapter()).marshal(digest);
 77     }
 78 
 79     public static byte[] initHmacSHA384Key()
 80         throws NoSuchAlgorithmException
 81     {
 82         KeyGenerator generator = KeyGenerator.getInstance("HmacSHA384");
 83         SecretKey secretKey = generator.generateKey();
 84         byte key[] = secretKey.getEncoded();
 85         return key;
 86     }
 87 
 88     public static String encodeHmacSHA384(byte data[], byte key[])
 89         throws Exception
 90     {
 91         SecretKey secretKey = new SecretKeySpec(key, "HmacSHA384");
 92         Mac mac = Mac.getInstance(secretKey.getAlgorithm());
 93         mac.init(secretKey);
 94         byte digest[] = mac.doFinal(data);
 95         return (new HexBinaryAdapter()).marshal(digest);
 96     }
 97 
 98     public static byte[] initHmacSHA512Key()
 99         throws NoSuchAlgorithmException
100     {
101         KeyGenerator generator = KeyGenerator.getInstance("HmacSHA512");
102         SecretKey secretKey = generator.generateKey();
103         byte key[] = secretKey.getEncoded();
104         return key;
105     }
106 
107     public static String encodeHmacSHA512(byte data[], byte key[])
108         throws Exception
109     {
110         SecretKey secretKey = new SecretKeySpec(key, "HmacSHA512");
111         Mac mac = Mac.getInstance(secretKey.getAlgorithm());
112         mac.init(secretKey);
113         byte digest[] = mac.doFinal(data);
114         return (new HexBinaryAdapter()).marshal(digest);
115     }
116 }

 

  1 package com._21cn.points.common.utils.encrypt.XXtea;
  2 
  3 import com._21cn.points.util.ByteFormat;
  4 
  5 public class XXTea
  6 {
  7 
  8     public XXTea()
  9     {
 10     }
 11 
 12     public static String encrypt(String plain, String charset, String hexKey)
 13         throws Exception
 14     {
 15         if (plain == null || charset == null || hexKey == null)
 16             return null;
 17         else
 18             return ByteFormat.toHex(encrypt(plain.getBytes(charset), ByteFormat.hexToBytes(hexKey)));
 19     }
 20 
 21     public static String decrypt(String cipherHex, String charset, String hexKey)
 22         throws Exception
 23     {
 24         if (cipherHex == null || charset == null || hexKey == null)
 25             return null;
 26         else
 27             return new String(decrypt(ByteFormat.hexToBytes(cipherHex), ByteFormat.hexToBytes(hexKey)), charset);
 28     }
 29 
 30     public static byte[] encrypt(byte plainData[], byte key[])
 31     {
 32         if (plainData == null || plainData.length == 0 || key == null)
 33             return null;
 34         else
 35             return toByteArray(encrypt(toIntArray(plainData, true), toIntArray(key, false)), false);
 36     }
 37 
 38     public static byte[] decrypt(byte cipherData[], byte key[])
 39     {
 40         if (cipherData == null || cipherData.length == 0 || key == null)
 41             return null;
 42         else
 43             return toByteArray(decrypt(toIntArray(cipherData, false), toIntArray(key, false)), true);
 44     }
 45 
 46     private static int[] encrypt(int v[], int k[])
 47     {
 48         int n = v.length - 1;
 49         if (n < 1)
 50             return v;
 51         if (k.length < 4)
 52         {
 53             int key[] = new int[4];
 54             System.arraycopy(k, 0, key, 0, k.length);
 55             k = key;
 56         }
 57         int z = v[n];
 58         int y = v[0];
 59         int delta = 0x9e3779b9;
 60         int sum = 0;
 61         for (int q = 6 + 52 / (n + 1); q-- > 0;)
 62         {
 63             sum += delta;
 64             int e = sum >>> 2 & 3;
 65             int p;
 66             for (p = 0; p < n; p++)
 67             {
 68                 y = v[p + 1];
 69                 z = v[p] += (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
 70             }
 71 
 72             y = v[0];
 73             z = v[n] += (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
 74         }
 75 
 76         return v;
 77     }
 78 
 79     public static String encode(String secrectText , String secrectKey){
 80         String params = null;
 81         try {
 82             if (secrectText == null || secrectText.trim() == "") {
 83             } else {
 84                 params = XXTea.encrypt(secrectText, "UTF-8", ByteFormat.toHex(secrectKey.getBytes()));
 85             }
 86         } catch (Exception e) {
 87             e.printStackTrace();
 88         }
 89         return params;
 90     }
 91 
 92     private static int[] decrypt(int v[], int k[])
 93     {
 94         System.out.println("-------Start--------");
 95     for(int i=0;i<v.length;i++){
 96         System.out.print(v[i]);
 97         System.out.print(" ");
 98     }
 99     System.out.println();
100     for(int i=0;i<k.length;i++){
101         System.out.print(k[i]);
102         System.out.print(" ");
103     }
104         
105     System.out.println("------End---------");
106         
107         
108         int n = v.length - 1;
109         if (n < 1)
110             return v;
111         if (k.length < 4)
112         {
113             int key[] = new int[4];
114             System.arraycopy(k, 0, key, 0, k.length);
115             k = key;
116         }
117         int z = v[n];
118         int y = v[0];
119         int delta = 0x9e3779b9;
120         int q = 6 + 52 / (n + 1);
121         for (int sum = q * delta; sum != 0; sum -= delta)
122         {
123             int e = sum >>> 2 & 3;
124             int p;
125             for (p = n; p > 0; p--)
126             {
127                 z = v[p - 1];
128                 y = v[p] -= (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
129             }
130 
131             z = v[n];
132             y = v[0] -= (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
133         }
134 
135         return v;
136     }
137 
138     private static int[] toIntArray(byte data[], boolean includeLength)
139     {
140         int n = (data.length & 3) != 0 ? (data.length >>> 2) + 1 : data.length >>> 2;
141         int result[];
142         if (includeLength)
143         {
144             result = new int[n + 1];
145             result[n] = data.length;
146         } else
147         {
148             result = new int[n];
149         }
150         n = data.length;
151         for (int i = 0; i < n; i++)
152             result[i >>> 2] |= (0xff & data[i]) << ((i & 3) << 3);
153 
154         return result;
155     }
156 
157     private static byte[] toByteArray(int data[], boolean includeLength)
158     {
159         int n = data.length << 2;
160         if (includeLength)
161         {
162             int m = data[data.length - 1];
163             if (m > n || m <= 0)
164                 return null;
165             n = m;
166         }
167         byte result[] = new byte[n];
168         for (int i = 0; i < n; i++)
169             result[i] = (byte)(data[i >>> 2] >>> ((i & 3) << 3) & 0xff);
170 
171         return result;
172     }
173 }

 

  1 package com._21cn.points.util;
  2 
  3 
  4 public class ByteFormat
  5 {
  6 
  7     private static final char HEX[] = {
  8         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
  9         'A', 'B', 'C', 'D', 'E', 'F'
 10     };
 11     private static final int ROW_BYTES = 16;
 12     private static final int ROW_QTR1 = 3;
 13     private static final int ROW_HALF = 7;
 14     private static final int ROW_QTR2 = 11;
 15 
 16     public ByteFormat()
 17     {
 18     }
 19 
 20     public static final String bytesToHexString(byte bArray[])
 21     {
 22         StringBuffer sb = new StringBuffer(bArray.length);
 23         for (int i = 0; i < bArray.length; i++)
 24         {
 25             String sTemp = Integer.toHexString(0xff & bArray[i]);
 26             if (sTemp.length() < 2)
 27                 sb.append(0);
 28             sb.append(sTemp.toUpperCase());
 29         }
 30 
 31         return sb.toString();
 32     }
 33 
 34     public static String toHex(byte buf[])
 35     {
 36         if (buf == null || buf.length == 0)
 37             return "";
 38         StringBuilder out = new StringBuilder();
 39         for (int i = 0; i < buf.length; i++)
 40             out.append(HEX[buf[i] >> 4 & 0xf]).append(HEX[buf[i] & 0xf]);
 41 
 42         return out.toString();
 43     }
 44 
 45     public static byte[] hexToBytes(String str)
 46     {
 47         if (str == null)
 48             return null;
 49         char hex[] = str.toCharArray();
 50         int length = hex.length / 2;
 51         byte raw[] = new byte[length];
 52         for (int i = 0; i < length; i++)
 53         {
 54             int high = Character.digit(hex[i * 2], 16);
 55             int low = Character.digit(hex[i * 2 + 1], 16);
 56             int value = high << 4 | low;
 57             if (value > 127)
 58                 value -= 256;
 59             raw[i] = (byte)value;
 60         }
 61 
 62         return raw;
 63     }
 64 
 65     public static String dumpHex(byte buf[])
 66     {
 67         if (buf == null)
 68             return "";
 69         else
 70             return dumpHex(buf, 0, buf.length);
 71     }
 72 
 73     public static String dumpHex(byte buf[], int offset, int numBytes)
 74     {
 75         if (buf == null || buf.length == 0)
 76             return "";
 77         if (offset >= buf.length)
 78             offset = buf.length - 1;
 79         if (numBytes > buf.length - offset)
 80             numBytes = buf.length - offset;
 81         StringBuffer out = new StringBuffer();
 82         byte save_buf[] = new byte[18];
 83         char hex_buf[] = new char[4];
 84         char idx_buf[] = new char[8];
 85         int rows = numBytes >> 4;
 86         int residue = numBytes & 0xf;
 87         int i;
 88         for (i = 0; i < rows; i++)
 89         {
 90             int hexVal = i * 16;
 91             idx_buf[0] = HEX[hexVal >> 12 & 0xf];
 92             idx_buf[1] = HEX[hexVal >> 8 & 0xf];
 93             idx_buf[2] = HEX[hexVal >> 4 & 0xf];
 94             idx_buf[3] = HEX[hexVal & 0xf];
 95             String idxStr = new String(idx_buf, 0, 4);
 96             out.append((new StringBuilder(String.valueOf(idxStr))).append(": ").toString());
 97             int j;
 98             for (j = 0; j < 16; j++)
 99             {
100                 save_buf[j] = buf[offset + i * 16 + j];
101                 hex_buf[0] = HEX[save_buf[j] >> 4 & 0xf];
102                 hex_buf[1] = HEX[save_buf[j] & 0xf];
103                 out.append(hex_buf[0]);
104                 out.append(hex_buf[1]);
105                 out.append(' ');
106                 if (j == 3 || j == 7 || j == 11)
107                     out.append(' ');
108                 if (save_buf[j] < 32 || save_buf[j] > 126)
109                     save_buf[j] = 46;
110             }
111 
112             String saveStr = new String(save_buf, 0, j);
113             out.append((new StringBuilder(" ; ")).append(saveStr).append("\n").toString());
114         }
115 
116         if (residue > 0)
117         {
118             int hexVal = i * 16;
119             idx_buf[0] = HEX[hexVal >> 12 & 0xf];
120             idx_buf[1] = HEX[hexVal >> 8 & 0xf];
121             idx_buf[2] = HEX[hexVal >> 4 & 0xf];
122             idx_buf[3] = HEX[hexVal & 0xf];
123             String idxStr = new String(idx_buf, 0, 4);
124             out.append((new StringBuilder(String.valueOf(idxStr))).append(": ").toString());
125             int j;
126             for (j = 0; j < residue; j++)
127             {
128                 save_buf[j] = buf[offset + i * 16 + j];
129                 hex_buf[0] = HEX[save_buf[j] >> 4 & 0xf];
130                 hex_buf[1] = HEX[save_buf[j] & 0xf];
131                 out.append(hex_buf[0]);
132                 out.append(hex_buf[1]);
133                 out.append(' ');
134                 if (j == 3 || j == 7 || j == 11)
135                     out.append(' ');
136                 if (save_buf[j] < 32 || save_buf[j] > 126)
137                     save_buf[j] = 46;
138             }
139 
140             for (; j < 16; j++)
141             {
142                 save_buf[j] = 32;
143                 out.append("   ");
144                 if (j == 3 || j == 7 || j == 11)
145                     out.append(" ");
146             }
147 
148             String saveStr = new String(save_buf, 0, j);
149             out.append((new StringBuilder(" ; ")).append(saveStr).append("\n").toString());
150         }
151         return out.toString();
152     }
153 
154     public static void main(String args[])
155     {
156         byte data[] = new byte[0x10000];
157         for (int i = 0; i < data.length; i++)
158             data[i] = (byte)i;
159 
160     }
161 
162 }

 

 1 package com._21cn.points.controller;
 2 
 3 import com._21cn.points.common.utils.encrypt.XXtea.MACTool;
 4 import com._21cn.points.common.utils.encrypt.XXtea.XXTea;
 5 import com._21cn.points.util.ByteFormat;
 6 
 7 public class Test {
 8     public static void main(String[] args) {
 9         String mobile="18922718369";
10         String userId="100230";
11         String tmpAccessToken="a3431aba6914fd671dc9bdaca7b1c4da";
12         String appId="1116416306";
13         String timeStamp="1510829685188";
14         String version="V1.0.0";
15         String appSecret = "UYB5elTW2ci897OtELMN1245XR6sxLkT"; // key,密钥
16 
17         String sign = "";
18         String params = "";
19         try {
20             params = XXTea.encrypt("mobile=" + mobile + "&userId=" + userId + "&tmpAccessToken=" + tmpAccessToken, "UTF-8", ByteFormat.toHex(appSecret.getBytes()));
21         } catch (Exception e) {
22         }
23         System.out.println("Params:"+params);
24         
25         System.out.println("HexSecret:"+ByteFormat.toHex(appSecret.getBytes()));
26         try {
27             String u =  XXTea.decrypt(params, "UTF-8", ByteFormat.toHex(appSecret.getBytes()));
28             System.out.println("--------------" + u);
29         } catch (Exception e1) {
30             e1.printStackTrace();
31         }
32         try {
33             sign = MACTool.encodeHmacSHA256((appId+timeStamp+version+params).getBytes(),appSecret.getBytes());
34             System.out.println(".......................    " + appId+timeStamp+version+params);
35             System.out.println("=====" + sign);
36             System.out.println("--------" + sign.length());
37         } catch (Exception e) {
38         }
39         System.out.println("mobile=" + mobile + "\n userId=" + userId + "\n tmpAccessToken=" + tmpAccessToken);
40         System.out.println("appId=" + appId+ "\n timeStamp="+timeStamp+ "\n version="+version );
41         System.out.println("params=" + params + "\n sign=" + sign );
42         
43     }
44 
45 }

 

推荐阅读