更新时间:2023-03-03 GMT+08:00
分享

session token签名

签名流程

  1. 构造待签名数据:"session_token="+sessionToken+"&timestamp="+timestamp+"&nonce="+nonce。

    其中,timestamp为当前服务器时间戳,可调用获取服务器时间戳接口获取,nonce为随机字符串,每次签名请重新生成,可为当前时间戳的16进制。

  2. 获取公钥publicKey,通过调用获取公钥接口获取。

    签名算法为RSA公钥加密,填充模式为RSA/ECB/OAEPWithSHA-256AndMGF1Padding,待签名数据加密后需要进行Base64编码。

Java签名代码实例

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

public class RSAUtils {
    public static final Provider provider = new BouncyCastleProvider();
    public static final String KEY_ALGORITHM = "RSA";
    public static final String BEGIN_PRI_KEY = "-----BEGIN RSA PRIVATE KEY-----";
    public static final String END_PRI_KEY = "-----END RSA PRIVATE KEY-----";
    public static final String BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
    public static final String END_PUB_KEY = "-----END PUBLIC KEY-----";

    //加密
    public static String encrypt(String input, String publicKey) {
        // 去除公钥开头、结束标识和换行符
        publicKey = publicKey.replaceAll(BEGIN_PUB_KEY, "").replaceAll(END_PUB_KEY, "").replace("\\n", "");
        try {
            byte[] enStrByte =  encrypt(input, getPublicRSAKey(publicKey));
            return Base64Utils.encodeToString(enStrByte);
        }catch (Exception e){
            throw new RuntimeException("Could not encrypt data ",e);
        }
    }

    private static PublicKey getPublicRSAKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
        X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64Utils.decodeFromString(key));
        KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM, provider);
        return kf.generatePublic(x509);
    }

    private static byte[] encrypt(String input, PublicKey publicKey)
            throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding", provider);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] re = cipher.doFinal(input.getBytes("UTF-8"));
        return re;
    }

    //解密
    public String decrypt(String input, String privateKey) {
        privateKey = privateKey.replaceAll(BEGIN_PRI_KEY, "").replaceAll(END_PRI_KEY, "").replace("\\n", "");
        try {
            byte[] bt = Base64.decodeBase64(input);
            byte[] decryptedData = RSAUtils.decrypt(bt, RSAUtils.getPrivateRSAKey(privateKey));
            return validateData(decryptedData);
        }catch (Exception e){
            return e.getMessage();
        }
    }

    private static byte[] decrypt(byte[] encrypted, PrivateKey privateKey)
            throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding", provider);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(encrypted);
    }

    public static PrivateKey getPrivateRSAKey(String key) throws InvalidKeySpecException, NoSuchAlgorithmException {
        PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(Base64Utils.decodeFromString(key));
        KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM, provider);
        return kf.generatePrivate(pkcs8);
    }

    private static String validateData(byte[] decryptedData) {
        String dataStr = new String(decryptedData, Charset.defaultCharset());
        if (dataStr!=null && dataStr.length() > 0){
            String[] split = dataStr.split("#");
            if (split.length > 1 && split[split.length-1].length() == String.valueOf(new Date().getTime()).length()) {
                try {
                    if (new Date().getTime() - Long.parseLong(split[split.length-1]) < 5*60*1000L){
                        return dataStr.substring(0,dataStr.length()-1-split[split.length-1].length());
                    }else {
                        throw new RuntimeException("operate time out");
                    }
                } catch (Exception e) {
                    throw new  RuntimeException("wrong timestamp ", e);
                }
            }else {
                return dataStr;
            }
        }
        return null;
    }
}

相关文档