【Java加解密系列】- SM4加解密

之前文章介绍过SM2生成密钥和加解密的代码实现过程,这篇文章主要介绍下SM4对称加密算法的代码实现,依然还是引用的BC库。代码实现比较简单,直接上代码:

public final class Sm4Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Sm4Utils.class);

    private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";

    private static volatile boolean initResult;

    private static Object lock = new Object();

    private static void init() {
        if (!initResult) {
            synchronized (lock) {
                if (!initResult) {
                    try {
                        Security.addProvider(new BouncyCastleProvider());
                        initResult = true;
                    } catch (Exception e) {
                        LOGGER.error("init failed:{}", e.getMessage(), e);
                    }
                }
            }
        }
    }

    /**
     * 加密
     * @param data 数据
     * @param key  秘钥
     * @return 密文
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        init();
        SecretKey secretKey = new SecretKeySpec(key, "SM4");
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data);
        return encryptedBytes;
    }

    /**
     * 解密
     * @param data 数据
     * @param key  秘钥
     * @return 明文
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        init();
        SecretKey secretKey = new SecretKeySpec(key, "SM4");
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(data);
        return decryptedBytes;
    }
}

跑个测试用例试一下:

public static void main(String args[]) throws Exception {
        String key = "abcdefghigklmnop";
        String data = "lenovo";
        String ciphertext = Base64.encodeBase64String(Sm4Utils.encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8")));
        System.out.println("ciphertext:" + ciphertext);
        String plaintext = new String(Sm4Utils.decrypt(Base64.decodeBase64(ciphertext), key.getBytes("UTF-8")), "UTF-8");
        System.out.println("plaintext:" + plaintext);
    }

输出结果如下:

ciphertext:iqGwAR5ZHRPoPO78RmK6AQ==
plaintext:lenovo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值