sunshine
2024-11-05 00b4581009af28098da4286a8ef9f4d72c7c5728
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package com.nova.sankuai.domain.api.jiniu;
 
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
 
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
 
/**
 * BairongSignature
 * 签名加密工具类-简化版
 *
 * @author zhenzhong.li
 * @date 18/1/4
 */
@Slf4j
public class BairongSignature {
    private static final String charset = "utf-8";
    private static final String signTypeSHA1 = "SHA1withRSA";
    private static final String signTypeSHA256 = "SHA256withRSA";
    private static final String signTypeMD5 = "MD5withRSA";
    //AES_256_cbc pkcs7
    private static final String algorithm = "AES/CBC/PKCS5Padding";
 
 
    /**
     * 加签
     *
     * @param signParams
     * @param privateKey
     * @return
     */
    public static String signMD5(Map<String, String> signParams, String privateKey) {
        return initSign(signTypeMD5, signParams, privateKey);
    }
 
    public static String signSHA1(Map<String, String> signParams, String privateKey) {
        return initSign(signTypeSHA1, signParams, privateKey);
    }
 
    public static String signSHA256(Map<String, String> signParams, String privateKey) {
        return initSign(signTypeSHA256, signParams, privateKey);
    }
 
    /**
     * 根据类型生成签名
     *
     * @param privateKey
     */
    private static String initSign(String signType, Map<String, String> signParams, String privateKey) {
        try {
            String content = getSignContent(signParams);
            PrivateKey priKey = getPrivateKeyFromPKCS8(privateKey);
            Signature signature = Signature.getInstance(signType);
            signature.initSign(priKey);
            if (isEmpty(charset)) {
                signature.update(content.getBytes());
            } else {
                signature.update(content.getBytes(charset));
            }
            byte[] signed = signature.sign();
            return Base64.encode(signed);
        } catch (Exception e) {
            System.out.println("生成签名异常:" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 验证签名
     *
     */
    public static boolean checkSignMD5(Map<String, String> signParams, String sign, String publicKey) {
        return rsa256CheckContent(signTypeMD5, signParams, sign, publicKey);
    }
 
    public static boolean checkSignSHA1(Map<String, String> signParams, String sign, String publicKey) {
        return rsa256CheckContent(signTypeSHA1, signParams, sign, publicKey);
    }
 
    public static boolean checkSignSHA256(Map<String, String> signParams, String sign, String publicKey) {
        return rsa256CheckContent(signTypeSHA256, signParams, sign, publicKey);
    }
 
    /**
     * 根据加签类型验证签名
     *
     * @param signParams
     * @param sign
     * @param publicKey
     * @return
     */
    private static boolean rsa256CheckContent(String signType, Map<String, String> signParams, String sign, String publicKey) {
        try {
            String content = getSignContent(signParams);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            Signature signature = Signature.getInstance(signType);
 
            signature.initVerify(pubKey);
            signature.update(content.getBytes(charset));
            boolean bverify = signature.verify(Base64.decode(sign));
            return bverify;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
 
 
    /**
     * RSA-公钥加密过程
     *
     * @param params
     * @param pubKey
     * @return
     * @throws Exception
     */
    public static String encryptRSA(Map<String, String> params, String pubKey) throws Exception {
        if (isEmpty(pubKey)) {
            throw new Exception("加密公钥为空, 请设置");
        }
        String context = getSignContent(params);
        PublicKey publicKey = getPublicKeyFromX509(pubKey);
        Cipher cipher;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(context.getBytes());
            return Base64.encode(output);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }
 
    /**
     * RSA-私钥解密过程
     *
     * @param context
     * @param priKey
     * @return
     * @throws Exception
     */
    public static String decryptRSA(String context, String priKey) throws Exception {
        if (isEmpty(priKey)) {
            throw new Exception("解密私钥为空, 请设置");
        }
        PrivateKey privateKey = getPrivateKeyFromPKCS8(priKey);
        Cipher cipher;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(Base64.decode(context));
            return new String(output);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }
 
    /**
     * 参数格式转换Map转String
     *
     * @param sortedParams
     * @return
     */
    public static String getSignContent(Map<String, String> sortedParams) {
        StringBuilder content = new StringBuilder();
        List<String> keys = new ArrayList<>(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;
        for (String key : keys) {
            String value = sortedParams.get(key);
            if (isNotEmpty(key) && isNotEmpty(value)) {
                content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
                index++;
            }
        }
        return content.toString();
    }
 
 
    /**
     * 私钥对象生成
     *
     */
    private static PrivateKey getPrivateKeyFromPKCS8(String priKey) throws Exception {
        PKCS8EncodedKeySpec priPKCS8;
        PrivateKey privateKey = null;
        if (isEmpty(priKey)) {
            return privateKey;
        }
        try {
            priPKCS8 = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(priKey));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            privateKey = keyf.generatePrivate(priPKCS8);
        } catch (Exception e) {
            System.out.println("私钥解析错误:" + e.getMessage());
        }
        return privateKey;
    }
 
    /**
     * 公钥对象生成
     *
     * @param pubKey
     * @return
     * @throws Exception
     */
    private static PublicKey getPublicKeyFromX509(String pubKey) throws Exception {
        PublicKey publicKey = null;
        if (isEmpty(pubKey)) {
            return publicKey;
        }
        try {
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(
                    new BASE64Decoder().decodeBuffer(pubKey));
            KeyFactory keyFactory;
            keyFactory = KeyFactory.getInstance("RSA");
            // 取公钥匙对象
            publicKey = keyFactory.generatePublic(bobPubKeySpec);
        } catch (Exception e) {
 
        }
        return publicKey;
    }
 
    /**
     * AES加密
     *
     * @param base64Key
     * @param text
     * @return
     * @throws Exception
     */
    public static String encryptAES(String base64Key, String text) {
        try {
            byte[] key = parseHexStr2Byte(base64Key);
            SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
            byte[] encryptBytes = cipher.doFinal(text.getBytes(charset));
            return parseByte2HexStr(encryptBytes);
        } catch (Exception e) {
            System.out.println("AES加密错误:" + e.getMessage());
        }
        return null;
    }
 
    /**
     * AES解密
     *
     * @param base64Key
     * @param text
     * @return
     * @throws Exception
     */
    public static String decryptAES(String base64Key, String text) {
        try {
            byte[] key = parseHexStr2Byte(base64Key);
            SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
            byte[] decryptBytes = cipher.doFinal(parseHexStr2Byte(text));
            return new String(decryptBytes, "UTF-8");
        } catch (Exception e) {
            log.error("AES解密错误:" + e.getMessage());
        }
        return null;
    }
 
    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
 
    /**
     * 将二进制转换成16进制
     *
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
 
 
    private static boolean isEmpty(String str) {
        return ((str == null) || (str.length() == 0));
    }
 
    private static boolean isNotEmpty(String str) {
        return ((str != null) && (str.length() > 0));
    }
 
 
}