Sunshine
2024-11-04 177f10973fd9bc1f0930369bb086ad9f0053440c
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
package com.nova.sankuai.infra.utils.baofu.rsa;
 
import com.nova.sankuai.infra.utils.baofu.FormatUtil;
 
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
 
/**
 * Created by BF100400 on 2017/4/17.
 */
public class SignatureUtils {
 
    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";
 
    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
 
    /**
     * @encryptStr 摘要
     * @signature  签名
     * @pubCerPath 公钥路径
     * 验签
     */
    public static boolean verifySignature(String pubCerPath, String encryptStr, String signature) throws Exception {
        PublicKey publicKey = RsaReadUtil.getPublicKeyFromFile(pubCerPath);
        return  verify(encryptStr.getBytes("UTF-8"),publicKey.getEncoded(), signature);
    }
    /**
     * @encryptStr 摘要
     * @pfxPath pfx证书路径
     * @priKeyPass 私钥
     * @charset 编码方式
     * 签名
     */
    public static String encryptByRSA(String encryptStr, String pfxPath, String priKeyPass)throws Exception {
        PrivateKey privateKey = RsaReadUtil.getPrivateKeyFromFile(pfxPath, priKeyPass);
        return  sign(encryptStr.getBytes("UTF-8") ,privateKey.getEncoded());
    }
 
    /**
     * 校验数字签名
     * @param data 已加密数据
     * @param keyBytes 公钥
     * @param sign 数字签名
     * @throws Exception
     *
     */
    public static boolean verify(byte[] data, byte[] keyBytes, String sign) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(FormatUtil.hex2Bytes(sign));
    }
 
    /**
     *
     * 用私钥对信息生成数字签名
     * @param data 已加密数据
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, byte[] keyBytes) throws Exception {
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return FormatUtil.byte2Hex(signature.sign());
    }
 
}