Your Name
2023-06-06 fe3b0f4a3c46892f08421dd4c4d0937fb8a87f93
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
package com.java110.acct.payment.adapt.bbgpay.lib;
 
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Enumeration;
 
import org.apache.commons.codec.binary.Base64;
 
/**
 * 验证证书公共类
 * 
 */
public class CAUtil {
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String KEY_ALGORITHM = "RSA";
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
 
    /**
     * 判断字符串是否为null或空 true为空
     */
    public static boolean isNullOrEmpty(String str) {
        return (str == null || str.length() == 0);
    }
 
    // 获取私钥
    public static PrivateKey getPrivateKey(InputStream is, String privateKeyPwd) throws Exception {
        KeyStore ks;
        try {
            ks = KeyStore.getInstance("PKCS12");
            char[] nPassword = null;
            if (isNullOrEmpty(privateKeyPwd)) {
                privateKeyPwd = null;
            } else {
                nPassword = privateKeyPwd.toCharArray();
            }
            ks.load(is, nPassword);
            is.close();
            Enumeration<?> enumas = ks.aliases();
            String keyAlias = null;
            if (enumas.hasMoreElements()) {
                keyAlias = (String) enumas.nextElement();
            }
            PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);
            return prikey;
        } catch (KeyStoreException e) {
            throw new Exception("获取KeyStore失败");
        } catch (FileNotFoundException e) {
            throw new Exception("无效的私钥地址");
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("读取私钥失败");
        } catch (CertificateException e) {
            throw new Exception("加载证书失败");
        } catch (IOException e) {
            throw new Exception("读取证书失败");
        } catch (UnrecoverableKeyException e) {
            throw new Exception("获取私钥失败");
        }
    }
 
    // 获取公钥
    public static PublicKey getPublicKey(String publicKeyAddr) throws Exception {
        try {
            CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
            FileInputStream bais = new FileInputStream(publicKeyAddr);
            X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(bais);
            bais.close();
            PublicKey pk = Cert.getPublicKey();
            return pk;
        } catch (CertificateException e) {
            throw new Exception("获取公钥失败");
        }
    }
 
    /**
     * RSA签名
     * 
     * @param localPrivKey
     *            私钥
     * @param plaintext
     *            需要签名的信息
     * @return byte[]
     * @throws Exception
     */
    public static byte[] signRSA(byte[] plainBytes, boolean useBase64Code, PrivateKey privKey) throws Exception {
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privKey);
        signature.update(plainBytes);
        // 如果是Base64编码的话,需要对签名后的数组以Base64编码
        if (useBase64Code) {
            return Base64.encodeBase64(signature.sign());
        } else {
            return signature.sign();
        }
    }
 
    /**
     * 验签操作
     * 
     * @param peerPubKey
     *            公钥
     * @param plainBytes
     *            需要验签的信息
     * @param signBytes
     *            签名信息
     * @return boolean
     */
    public static boolean verifyRSA(byte[] plainBytes, byte[] signBytes, boolean useBase64Code, PublicKey pubKey) throws Exception {
        boolean isValid = false;
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(plainBytes);
        // 如果是Base64编码的话,需要对验签的数组以Base64解码
        if (useBase64Code) {
            isValid = signature.verify(Base64.decodeBase64(signBytes));
        } else {
            isValid = signature.verify(signBytes);
        }
        return isValid;
    }
    
    /**
     * SHA256withRSA签名(RSA2)
     * 
     */
    public static String rsa256Sign(String content, String charset, String privateKey) throws Exception {
        if (isNullOrEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        if (isNullOrEmpty(privateKey)) {
            return null;
        }
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        byte[] encodedKey = StreamUtil.readText(new ByteArrayInputStream(privateKey.getBytes())).getBytes();
        encodedKey = Base64.decodeBase64(encodedKey);
        PrivateKey priKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        if (isNullOrEmpty(charset)) {
            signature.update(content.getBytes());
        } else {
            signature.update(content.getBytes(charset));
        }
        byte[] signed = signature.sign();
        return new String(Base64.encodeBase64(signed));
    }
 
    /**
     * SHA256withRSA验签(RSA2)
     * 
     */
    public static boolean rsa256Verify(byte[] content, String sign, String publicKey) throws Exception {
        if (isNullOrEmpty(publicKey)) {
            return false;
        }
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        StringWriter writer = new StringWriter();
        StreamUtil.io(new InputStreamReader(new ByteArrayInputStream(publicKey.getBytes())), writer);
        byte[] encodedKey = writer.toString().getBytes();
        encodedKey = Base64.decodeBase64(encodedKey);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(content);
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }
}