3DES加密算法-预登记接口

3DES加密算法-预登记接口

背景

对接第三方的预登记接口

一、请求地址:http://XXX.com

二、请求参数:{‘message’:”加密后字符串”}
字符串加密步骤:

1
2
3
4
5
6
7
8
9
1、加密前字符串,json格式——》{"name":"telphone","param":"手机号码"}
或{"name":"openid","param":"openid号码"}
2、使用TripleDES(3Des)加密算法,加密密钥为 05WOB22Z9jdrHxLVjGxAL47F
3、将加密后的字符串进行url编码
字符串加密例子
原字符串:{"name":"telphone","param":"18520278383"}
加密后字符串:AvR7ai1cixdbIiv1ngMwnYbmPhKKbDyi51k4GyL9y+3tqfzd4MeFNm/vwA/AoSIn
加密后字符串经过url编码:AvR7ai1cixdbIiv1ngMwnYbmPhKKbDyi51k4GyL9y%2B3tqfzd4MeFNm%2FvwA%2FAoSIn
解密字符串:{"name":"telphone","param":"18520278383"}

按照说明,通过HTTP(S)协议,调用接口进行预登记的功能。

代码实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package uitl;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
* 3DES又称Triple DES,是DES加密算法的一种模式,它使用3条56位的密钥对3DES数据进行三次加密。
*/
public class EncrypDES3 {
// KeyGenerator 提供对称密钥生成器的功能,支持各种算法
private KeyGenerator keygen;
// SecretKey 负责保存对称密钥
private SecretKey deskey;
// Cipher负责完成加密或解密工作
private Cipher c;
// 该字节数组负责保存加密的结果
//private byte[] cipherByte;
//保存密钥
private byte[] keyByte;

/**
* 构造方法
* @param desKeyString 密钥
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
*/
public EncrypDES3(String desKeyString) throws NoSuchAlgorithmException, NoSuchPaddingException {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// 实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
keygen = KeyGenerator.getInstance("DESede");
if ("".equals(desKeyString)) {
System.out.println("密钥是空的");
// 生成密钥
deskey = keygen.generateKey();
} else {
System.out.println("密钥不为空");
deskey = new SecretKeySpec(desKeyString.getBytes(), "DESede");
}
//保存密钥
keyByte = deskey.getEncoded();
// 生成Cipher对象,指定其支持的DES算法
c = Cipher.getInstance("DESede");
}

/**
* 对字符串加密
*
* @param str
* @return
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws IOException
*/
public String Encrytor(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, IOException {
// 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
c.init(Cipher.ENCRYPT_MODE, deskey);
// 加密,结果保存进cipherByte
byte[] buf = c.doFinal(str.getBytes("utf-8"));
String encontent=new sun.misc.BASE64Encoder().encode(buf);
//保存密钥
//saveFile("C:\\Users\\Zero\\Desktop\\key.dat", Base64Utils.encode(keyByte));
return encontent;
}

/**
* 对字符串解密
*
* @param secretData
* @return
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws IOException
*/
public String Decryptor(String secretData) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, IOException {
// 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式
c.init(Cipher.DECRYPT_MODE, deskey);
byte[] buf = c.doFinal(Base64Utils.decode(secretData.toCharArray()));
String decontent = new String(buf);
return decontent;
}

/**
* 加载文件
*
* @param file
* @return
* @throws IOException
*/
public static String loadFile(String file) throws IOException {
File f = new File(file);
FileReader fr = new FileReader(f);
BufferedReader bf = new BufferedReader(fr);
StringBuilder msg = new StringBuilder();
String str;
while ((str = bf.readLine()) != null) {
msg.append(str + "\n");
}
msg.deleteCharAt(msg.length() - 1);
bf.close();
return msg.toString();
}

/**
* 保存文件
*
* @param file
* @param message
* @throws IOException
*/
public static void saveFile(String file, String message) throws IOException {
File f = new File(file);
if (!f.exists()) {
f.createNewFile();
}
FileOutputStream fos = new FileOutputStream(f);
fos.write(message.getBytes());
fos.close();
}

/**
* 加密文本文件
*
* @param sourceFile
* @param desFile
* @throws IOException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws InvalidKeyException
*/
public static void Encrytor(String sourceFile, String desFile) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
EncrypDES3 des = new EncrypDES3(null);
String msg = loadFile(sourceFile);
String encontent = des.Encrytor(msg);
saveFile(desFile, encontent);
}

/**
* 解密文本文件
*
* @param sourceFile
* @param desFile
* @param keyFile
* @throws IOException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws InvalidKeyException
*/
public static void Decryptor(String sourceFile, String desFile, String keyFile) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
EncrypDES3 des = new EncrypDES3(null);
String msg = loadFile(sourceFile);
String key = loadFile(keyFile);
String decontent = des.Decryptor(msg);
saveFile(desFile, decontent);
}

/**
* 测试方法
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String KEY = "05WOB22Z9jdrHxLVjGxAL47F";
EncrypDES3 des = new EncrypDES3(KEY);
String jsonString = "{\"name\":\"telphone\",\"param\":\"18520278383\"}";
System.out.println("【源参数】"+jsonString);
String desString = des.Encrytor(jsonString);
System.out.println("【des加密后】"+desString);
String urlEncoderString = URLEncoder.encode(desString, "utf-8");
System.out.println("【url加密后】"+urlEncoderString);
System.out.println("【des解密后】"+des.Decryptor("AvR7ai1cixdbIiv1ngMwnYbmPhKKbDyi51k4GyL9y+3tqfzd4MeFNm/vwA/AoSIn"));


//String msg = "{\"name\":\"telphone\",\"param\":\"18520278383\"}";
//System.out.println("【加密前】:" + msg);
//EncrypDES3 des = new EncrypDES3("05WOB22Z9jdrHxLVjGxAL47F");
//System.out.println("【加密后】:" + des.Encrytor(msg));
//Encrytor("C:\\Users\\Zero\\Desktop\\hint.txt", "C:\\Users\\Zero\\Desktop\\encontent.txt");
//Decryptor("C:\\Users\\Zero\\Desktop\\encontent.txt", "C:\\Users\\Zero\\Desktop\\decontent.txt", "C:\\Users\\Zero\\Desktop\\key.dat");
}

}
//=======================================万恶的分割线================================================================
package uitl;

public class Base64Utils {

static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
static private byte[] codes = new byte[256];

static {
for (int i = 0; i < 256; i++)
codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
codes[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
codes[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}

/**
* 将原始数据编码为base64编码
*/
static public String encode(byte[] data) {
char[] out = new char[((data.length + 2) / 3) * 4];
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
boolean quad = false;
boolean trip = false;
int val = (0xFF & (int) data[i]);
val <<= 8;
if ((i + 1) < data.length) {
val |= (0xFF & (int) data[i + 1]);
trip = true;
}
val <<= 8;
if ((i + 2) < data.length) {
val |= (0xFF & (int) data[i + 2]);
quad = true;
}
out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 1] = alphabet[val & 0x3F];
val >>= 6;
out[index + 0] = alphabet[val & 0x3F];
}

return new String(out);
}

/**
* 将base64编码的数据解码成原始数据
*/
static public byte[] decode(char[] data) {
int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 && data[data.length - 1] == '=')
--len;
if (data.length > 1 && data[data.length - 2] == '=')
--len;
byte[] out = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix = 0; ix < data.length; ix++) {
int value = codes[data[ix] & 0xFF];
if (value >= 0) {
accum <<= 6;
shift += 6;
accum |= value;
if (shift >= 8) {
shift -= 8;
out[index++] = (byte) ((accum >> shift) & 0xff);
}
}
}
if (index != out.length)
throw new Error("miscalculated data length!");
return out;
}
}

源码地址

参考链接:

https://blog.csdn.net/yinhuaiya/article/details/52382741

-------------已经触及底线 感谢您的阅读-------------

本文标题:3DES加密算法-预登记接口

文章作者:趙小傑~~

发布时间:2018年03月13日 - 16:35:08

最后更新:2019年07月26日 - 23:32:12

原始链接:https://cnsyear.com/posts/1473ce2d.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%