package com.alipay.face.verify.fintechfacedemo.utils;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class RSAUtils {
    /**
     * 非对称加密密钥算法
     */
    public static final String RSA = "RSA";
    /**
     * 加密填充方式
     */
    public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";
    /**
     * 公钥
     */
    private static final String PUBLICKEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApCMA3HuXpuNLdBgOYPqcCHx0rPggUNE/F/9FgQ/EaNvk26la+m+lgLLLaRRNdmQxdn3dg+9vvahfXr/lxDfZJ9VDv2mK/Rnnua1/o75vGF6+MD/lBc02+uqD07N9EiQlNREQb3Q/5d7Kc7H+eJUix7AU9YAol9SrOU6m6lI32GVnVdqrY7x9WQt02OgFag0jgzNexTdx1TM35kNa8ZiohlpSgvoKgmeKmHgwWKRsMpZ+/RbAWQZLkofoX4P7kqdGxNZtGWVHEcjphJqfx6q7CyFG2qTiGqFhAYu34CEIXWxQy5trUIiSMEBucGyPw+r8DSvoPT0tJ8tWthW1Oc23SQIDAQAB";

    /**
     * 加密认证参数
     */
    public static String encrypt(byte[] identityParam) {
        try {
            byte[] publicKeyDecode = Base64Util.decodeBase64(PUBLICKEY.getBytes());
            byte[] rsaCryptoBytes = encryptByPublicKey(identityParam, publicKeyDecode);
            return new String(Base64Util.encodeBase64(rsaCryptoBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用公钥对字符串进行加密
     *
     * @param data 原文
     */
    private static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
        // 得到公钥
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PublicKey keyPublic = kf.generatePublic(keySpec);
        // 加密数据
        Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
        cp.init(Cipher.ENCRYPT_MODE, keyPublic);
        return cp.doFinal(data);
    }

}
