package com.allinpay.demo.util;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * @Description
 * @Author meixf@allinpay.com
 * @Date 2022年3月3日
 **/
public class SM4Util {

    private static final String KEY_ALGORITHM = "SM4";
    private static final String CRYPT_ALGORITHM = "SM4/ECB/PKCS5Padding";


    static{
        if(Security.getProvider("BC") == null){
            BouncyCastleProvider prvd = new BouncyCastleProvider();  //密码不能用特殊符号
            Security.addProvider(prvd);
        }
    }


    public static String encrptWithBase64(String source, String key,String encoding) throws Exception{
        Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM, "BC");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(encoding), KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] result = cipher.doFinal(source.getBytes(encoding));// 加密
        return Base64.encodeBase64String(result);
    }


    public static String decryptWithBase64(String encryptedMsg, String key, String encoding) throws Exception{
        Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM, "BC");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(encoding), KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] result = cipher.doFinal(Base64.decodeBase64(encryptedMsg));
        return new String(result, encoding);
    }

    public static void main(String[] args) throws Exception{
    }
}
