Help Center/ OneAccess/ API Reference/ Appendix/ Signing a Session Token
Updated on 2024-12-30 GMT+08:00

Signing a Session Token

Signing Process

  1. Construct the data to be signed: "session_token="+sessionToken+"&timestamp="+timestamp+"&nonce="+nonce.

    In the data, timestamp indicates the timestamp of the current server. The timestamp can be obtained by calling the API used to obtain the server timestamp. nonce is a random character string generated for each signature. The string can be a hexadecimal string of the current timestamp.

  2. Obtain a public key by calling the corresponding API.

    The signature algorithm is RSA, and the padding mode is RSA/ECB/OAEPWithSHA-256AndMGF1Padding. The encrypted data to be signed must be encoded using Base64.

Java Code Signing Example

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-----";

    // Encryption
    public static String encrypt(String input, String publicKey) {
        // Remove the start and end identifiers and newline characters from the public key.
        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;
    }

    // Decryption
    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;
    }
}