package com.huimv.management.rsa;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * @Author yinhao
 * @Date 2021/4/30 13:22
 * @Description
 */
public class SignRSAUtil {

    public static void main(String[] args) throws Exception {
        String channelId = "1018";
        int random = (int) ((Math.random() * 9 + 1) * 100000);
        long timestamp = System.currentTimeMillis();
        String data = channelId + ";" + random + ";" + timestamp;

//        String sign = getPinAnSign(data.getBytes(StandardCharsets.UTF_8), Constants.RSA_SIGN_PRIVATE_KEY);
//        System.out.println(sign);
//        String decrypt = decrypt(sign, Constants.RSA_SIGN_PUBLIC_KEY);
//        System.out.println(decrypt);


    }

    public static String getPinAnSign(byte[] data, String privatekey) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privatekey);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey1 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(privateKey1);
        signature.update(data);

        return new String(Base64.encodeBase64(signature.sign()));
    }

    public static String decrypt(String data, String publicKey) {
        try {
            byte[] keyBytes = Base64.decodeBase64(publicKey);
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128);
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(data.getBytes(), "AES"));
            byte[] decrypt = cipher.doFinal(keyBytes);
            String encode = new String(decrypt);
            return encode;
        } catch (
                NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;


    }


}
