Pu Zhibing
4 天以前 db0b7644a9a5a62ac2da3cf571fee41bb8b6974f
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
package com.ruoyi.jianguan.elutong.core;
 
import org.apache.commons.lang3.StringUtils;
 
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
 
public class SignatureTools {
 
    public static final String PUBLIC_KEY = "RSAPublicKey";
    public static final String PRIVATE_KEY = "RSAPrivateKey";
    private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
 
    /**
     * sha256WithRsa 加签
     *
     * @param content      待签名的字符串
     * @param priKeyBase64 base64编码的私钥
     * @return base64编码的签名
     */
    public static String rsa256Sign(String content, String priKeyBase64) {
        byte[] signed = sign(SignAlgorithm.SHA256withRSA, content.getBytes(DEFAULT_CHARSET), Base64Tools.decodeFromString(priKeyBase64));
        return Base64Tools.encodeToString(signed);
    }
 
    /**
     * sha256WithRsa 验签
     *
     * @param content      待验签的字符串
     * @param pubKeyBase64 base64编码的公钥
     * @param signBase64   base64编码签名
     * @return 签名是否正确
     */
    public static boolean rsa256Verify(String content, String pubKeyBase64, String signBase64) {
        return verify(SignAlgorithm.SHA256withRSA, content.getBytes(DEFAULT_CHARSET),
                Base64Tools.decodeFromString(signBase64), Base64Tools.decodeFromString(pubKeyBase64));
    }
 
    public static byte[] sign(SignAlgorithm algorithm, byte[] content, byte[] key) {
        try {
            PrivateKey priKey = generatePrivateKey(algorithm, key);
            Signature signature = Signature.getInstance(algorithm.getValue());
            signature.initSign(priKey);
            signature.update(content);
            byte[] signed = signature.sign();
            return signed;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    public static boolean verify(SignAlgorithm algorithm, byte[] content, byte[] sign, byte[] key) {
        try {
            Signature signature = Signature.getInstance(algorithm.getValue());
            PublicKey publicKey = generatePublicKey(algorithm, key);
            signature.initVerify(publicKey);
            signature.update(content);
            return signature.verify(sign);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
 
    public static PrivateKey generatePrivateKey(SignAlgorithm algorithmType, byte[] key)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        return generatePrivateKey(algorithmType, new PKCS8EncodedKeySpec(key));
    }
 
    public static PrivateKey generatePrivateKey(SignAlgorithm algorithmType, KeySpec keySpec)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        return KeyFactory.getInstance(algorithmType.getType()).generatePrivate(keySpec);
    }
 
    public static PublicKey generatePublicKey(SignAlgorithm algorithm, byte[] key)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        return generatePublicKey(algorithm, new X509EncodedKeySpec(key));
    }
 
    public static PublicKey generatePublicKey(SignAlgorithm algorithm, KeySpec keySpec)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        return KeyFactory.getInstance(algorithm.getType()).generatePublic(keySpec);
    }
 
    public static String buildSignStr(Object object) {
        if (object == null) {
            return null;
        }
        Map map = new HashMap();
 
        for (Field field : object.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                if ("sign".equals(field.getName())) {
                    continue;
                }
                if ("filename".equals(field.getName())) {
                    continue;
                }
 
                map.put(field.getName(), field.get(object));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        TreeMap<String, String> treeMap = new TreeMap<>(map);
        StringBuffer strBuffer = new StringBuffer();
        treeMap.entrySet().forEach(i -> {
            if (i.getValue() == null) {
                return;
            }
            if (StringUtils.isBlank(i.getValue())) {
                return;
            }
            strBuffer.append(i.getKey()).append("=").append(String.valueOf(i.getValue())).append("&");
        });
        String signStr = strBuffer.substring(0, strBuffer.length() - 1);
        return signStr;
    }
 
 
}