Java SM4 工具类,依赖bcprov-jdk15on

Java实现SM4国密加解密,依赖bcprov-jdk15on.jar

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.70</version>
</dependency>
/**
 * @author EvanY
 * @since 2021/11/30
 */
public class SM4Utils {
    public static final String SM4_ECB_PKCS7 = "SM4/ECB/PKCS7Padding";
    public static final String SM4_CBC_PKCS7 = "SM4/CBC/PKCS7Padding";
    public static final String PROVIDER_BC = "BC";


    public static byte[] encryptWithSM4(byte[] key, byte[] iv, byte[] input) throws Exception {
        return cryptWithSM4(key, iv, input, Cipher.ENCRYPT_MODE, SM4_CBC_PKCS7, PROVIDER_BC);
    }

    public static byte[] encryptWithSM4(byte[] key, byte[] iv, byte[] input, String algorithm, String provider) throws Exception {
        return cryptWithSM4(key, iv, input, Cipher.ENCRYPT_MODE, algorithm, provider);
    }

    public static byte[] decryptWithSM4(byte[] key, byte[] iv, byte[] input) throws Exception {
        return cryptWithSM4(key, iv, input, Cipher.DECRYPT_MODE, SM4_CBC_PKCS7, PROVIDER_BC);
    }

    public static byte[] decryptWithSM4(byte[] key, byte[] iv, byte[] input, String algorithm, String provider) throws Exception {
        return cryptWithSM4(key, iv, input, Cipher.DECRYPT_MODE, algorithm, provider);
    }

    public static byte[] cryptWithSM4(byte[] key, byte[] iv, byte[] input, int mode, String algorithm, String provider) throws Exception {
        SecretKeySpec spec = new SecretKeySpec(key, "SM4");
        Cipher cipher;
        if (provider == null || provider.isEmpty()) {
            cipher = Cipher.getInstance(algorithm);
        } else {
            cipher = Cipher.getInstance(algorithm, provider);
        }
        if (iv == null || iv.length == 0) {
            cipher.init(mode, spec);
        } else {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
            cipher.init(mode, spec, ivParameterSpec);
        }
        return cipher.doFinal(input);
    }

    static {
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }
}
posted @ 2024-02-24 17:01  yy299  阅读(1380)  评论(0)    收藏  举报