SM4加密解密测试学习代码

/**
 * sm4加密算法工具类
 * @explain sm4加密、解密与加密结果验证 可逆算法
 * @Autor:jingyao
 */
public class Sm4Util {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用:PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制;256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    /**
     * 生成ECB暗号
     * @explain ECB模式(电子密码本模式:Electronic codebook)
     * @param algorithmName 算法名称
     * @param mode 模式
     * @param key
     * @return
     * @throws Exception
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /**
     * 自动生成密钥
     * @explain
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    public static byte[] generateKey() throws Exception {
        return generateKey(DEFAULT_KEY_SIZE);
    }


    //加密******************************************
    /**
     * @explain 系统产生秘钥
     * @param keySize
     * @return
     * @throws Exception
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    /**
     * sm4加密
     * @explain 加密模式:ECB 密文长度不固定,会随着被加密字符串长度的变化而变化
     * @param hexKey 16进制密钥(忽略大小写)
     * @param paramStr 待加密字符串
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encryptEcb(String hexKey, String paramStr) throws Exception {
        String cipherText = "";
        // 16进制字符串-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // String-->byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 加密后的数组
        byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
        // byte[]-->hexString
        cipherText = ByteUtils.toHexString(cipherArray);
        return cipherText;
    }

    /**
     * 加密模式之Ecb
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);//声称Ecb暗号,通过第二个参数判断加密还是解密
        return cipher.doFinal(data);
    }

    //解密****************************************
    /**
     * sm4解密
     * @explain 解密模式:采用ECB
     * @param hexKey 16进制密钥
     * @param cipherText 16进制的加密字符串(忽略大小写)
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptEcb(String hexKey, String cipherText) throws Exception {
        // 用于接收解密后的字符串
        String decryptStr = "";
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // hexString-->byte[]
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        // byte[]-->String
        decryptStr = new String(srcData, ENCODING);
        return decryptStr;
    }

    /**
     * 解密
     * @explain
     * @param key
     * @param cipherText
     * @return
     * @throws Exception
     */
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);//生成Ecb暗号,通过第二个参数判断加密还是解密
        return cipher.doFinal(cipherText);
    }

    /**
     * 校验加密前后的字符串是否为同一数据
     * @explain
     * @param hexKey 16进制密钥(忽略大小写)
     * @param cipherText 16进制加密后的字符串
     * @param paramStr 加密前的字符串
     * @return 是否为同一数据
     * @throws Exception
     */
    public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        // 用于接收校验结果
        boolean flag = false;
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // 将16进制字符串转换成数组
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        // 将原字符串转换成byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 判断2个数组是否一致
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }

}
  • 14
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是 Java 实现的 SM4 加密解密代码: ```java import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class SM4Utils { private String secretKey = ""; // 密钥 private String iv = ""; // 向量 private boolean hexString = false; public SM4Utils() { } public SM4Utils(String secretKey) { this.secretKey = secretKey; this.iv = secretKey.substring(0, 16); } public SM4Utils(String secretKey, String iv) { this.secretKey = secretKey; this.iv = iv; } public void setHexString(boolean hexString) { this.hexString = hexString; } public String encryptData_ECB(String plainText) throws Exception { byte[] keyBytes = hexString ? Base64.decodeBase64(secretKey) : secretKey.getBytes("UTF-8"); byte[] plainBytes = hexString ? Base64.decodeBase64(plainText) : plainText.getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "SM4")); byte[] encryptedBytes = cipher.doFinal(plainBytes); return hexString ? Base64.encodeBase64String(encryptedBytes) : new String(encryptedBytes, "UTF-8"); } public String decryptData_ECB(String cipherText) throws Exception { byte[] keyBytes = hexString ? Base64.decodeBase64(secretKey) : secretKey.getBytes("UTF-8"); byte[] encryptedBytes = hexString ? Base64.decodeBase64(cipherText) : cipherText.getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "SM4")); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return hexString ? Base64.encodeBase64String(decryptedBytes) : new String(decryptedBytes, "UTF-8"); } public String encryptData_CBC(String plainText) throws Exception { byte[] keyBytes = hexString ? Base64.decodeBase64(secretKey) : secretKey.getBytes("UTF-8"); byte[] plainBytes = hexString ? Base64.decodeBase64(plainText) : plainText.getBytes("UTF-8"); byte[] ivBytes = hexString ? Base64.decodeBase64(iv) : iv.getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "SM4"), new IvParameterSpec(ivBytes)); byte[] encryptedBytes = cipher.doFinal(plainBytes); return hexString ? Base64.encodeBase64String(encryptedBytes) : new String(encryptedBytes, "UTF-8"); } public String decryptData_CBC(String cipherText) throws Exception { byte[] keyBytes = hexString ? Base64.decodeBase64(secretKey) : secretKey.getBytes("UTF-8"); byte[] encryptedBytes = hexString ? Base64.decodeBase64(cipherText) : cipherText.getBytes("UTF-8"); byte[] ivBytes = hexString ? Base64.decodeBase64(iv) : iv.getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "SM4"), new IvParameterSpec(ivBytes)); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return hexString ? Base64.encodeBase64String(decryptedBytes) : new String(decryptedBytes, "UTF-8"); } public static void main(String[] args) throws Exception { SM4Utils sm4 = new SM4Utils("1234567890123456"); String plainText = "Hello, world!"; String cipherText = sm4.encryptData_CBC(plainText); String decryptedText = sm4.decryptData_CBC(cipherText); System.out.println("Plain Text: " + plainText); System.out.println("Cipher Text: " + cipherText); System.out.println("Decrypted Text: " + decryptedText); } } ``` 其中,`SM4Utils` 类包含了 ECB 和 CBC 两种模式的加密解密方法,可以根据需要选择。在主函数中,演示了如何使用 `SM4Utils` 类进行加密解密。注意,这里使用的是 Apache Commons Codec 库来进行 Base64 编解码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

l411723

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值