tj
2025-03-28 b1ab565909e471dde643755e93633cb84872733b
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
package com.mzl.flower.utils.alipay;
 
 
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
 
 
public class SignUtils {
 
    private static final String ALGORITHM = "RSA";
 
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
 
    private static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA";
 
    private static final String DEFAULT_CHARSET = "UTF-8";
 
    private static String getAlgorithms(boolean rsa2) {
        return rsa2 ? SIGN_SHA256RSA_ALGORITHMS : SIGN_ALGORITHMS;
    }
 
    public static String sign(String content, String privateKey, boolean rsa2) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    Base64.getDecoder().decode(privateKey));
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
 
            java.security.Signature signature = java.security.Signature
                    .getInstance(getAlgorithms(rsa2));
 
            signature.initSign(priKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));
 
            byte[] signed = signature.sign();
            return Base64.getEncoder().encodeToString(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
}