package com.jiayue.ipfcst.common.core.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.jasypt.encryption.StringEncryptor;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * 非对称加密
 *
 * @author zzy
 * @version 1.0
 * @since 2019/8/8 11:17
 */
@Slf4j
public class RSAEncrypt implements StringEncryptor {


    //非对称密钥算法
    private static final String KEY_ALGORITHM = "RSA";

    private static final String CHARSET_NAME = "UTF-8";

    //公钥
    private static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJG5x3e0r4/cgU/8cy158AzhPf1huiMDqPnazaIzjMId3N43dST5ODOvxe5I63/s8E2cC83lucZm33Dw8K9syK8CAwEAAQ==";

    @Override
    public String encrypt(String message) {
        return null;
    }

    @Override
    public String decrypt(String encryptedMessage) {
        String message = "";
        try {
            //实例化密钥工厂
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //初始化公钥
            //密钥材料转换
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(PUBLIC_KEY));
            //产生公钥
            PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
            //数据解密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, pubKey);
            message = new String(cipher.doFinal(Base64.decodeBase64(encryptedMessage)), CHARSET_NAME);
        } catch (Exception e) {
            log.error("解码失败:", e);
        }
        return message;
    }
}
