package com.sd.cavphmi.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Security;
import java.util.Base64;

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

public class SM4CryptoHelper {

    private static final String ALGORITHM = "SM4";
    private static final String TRANSFORMATION_ECB = "SM4/ECB/PKCS7Padding";
    private static final String TRANSFORMATION_CBC = "SM4/CBC/PKCS7Padding";

    static {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
        Security.addProvider(new BouncyCastleProvider());
    }


    // ECB模式加密
    public static String  encryptECB(byte[] key, byte[] data) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION_ECB, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, ALGORITHM));
        byte[] encrypted = cipher.doFinal(data);
         return Base64.getEncoder().encodeToString(encrypted);
    }


    // CBC模式加密（需IV参数）
    public static byte[] encryptCBC(byte[] key, byte[] iv, byte[] data) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION_CBC, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, ALGORITHM), new IvParameterSpec(iv));
        return cipher.doFinal(data);
    }

}
