SM4(ECB模式加密)工具类

1 篇文章 0 订阅
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Base64;

public class Sm4EcbUtils {

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

    private static final String ALGORITHM = "SM4/ECB/PKCS5Padding";
    private static final String TRANSFORMATION = "SM4";

    /**
     * SM4 ECB模式加密
     * @param key 密钥,必须是16字节
     * @param data 明文数据
     * @return 密文,Base64编码
     * @throws RuntimeException 包含可能的加密异常
     */
    public static String encrypt(byte[] key, String data) throws RuntimeException {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
            SecretKeySpec sm4Key = new SecretKeySpec(key, TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, sm4Key);

            byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
                 IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Encryption failed: " + e.getMessage(), e);
        }
    }

    /**
     * SM4 ECB模式解密
     * @param key 密钥,必须是16字节
     * @param base64EncryptedData Base64编码的密文数据
     * @return 解密后的明文数据
     * @throws RuntimeException 包含可能的解密异常
     */
    public static String decrypt(byte[] key, String base64EncryptedData) throws RuntimeException {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
            SecretKeySpec sm4Key = new SecretKeySpec(key, TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, sm4Key);

            byte[] encryptedBytes = Base64.getDecoder().decode(base64EncryptedData);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
                 IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Decryption failed: " + e.getMessage(), e);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Java语言实现的SM4-ECB加密工具类,供参考: ```java import org.bouncycastle.crypto.engines.SM4Engine; import org.bouncycastle.crypto.modes.ECBBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.util.encoders.Hex; public class SM4Util { /** * SM4 ECB加密 * * @param key 加密密钥,长度为16字节 * @param data 待加密数据 * @return 加密结果,16进制字符串 */ public static String encryptECB(String key, String data) { try { byte[] keyBytes = Hex.decode(key); byte[] dataBytes = Hex.decode(data); // 初始化SM4引擎 SM4Engine engine = new SM4Engine(); ECBBlockCipher cipher = new ECBBlockCipher(engine); cipher.init(true, new KeyParameter(keyBytes)); // 加密 byte[] out = new byte[dataBytes.length]; int len = cipher.processBlock(dataBytes, 0, dataBytes.length, out, 0); cipher.doFinal(out, len); // 转换为16进制字符串 return Hex.toHexString(out); } catch (Exception e) { e.printStackTrace(); return null; } } /** * SM4 ECB解密 * * @param key 解密密钥,长度为16字节 * @param data 待解密数据,16进制字符串 * @return 解密结果 */ public static String decryptECB(String key, String data) { try { byte[] keyBytes = Hex.decode(key); byte[] dataBytes = Hex.decode(data); // 初始化SM4引擎 SM4Engine engine = new SM4Engine(); ECBBlockCipher cipher = new ECBBlockCipher(engine); cipher.init(false, new KeyParameter(keyBytes)); // 解密 byte[] out = new byte[dataBytes.length]; int len = cipher.processBlock(dataBytes, 0, dataBytes.length, out, 0); cipher.doFinal(out, len); // 转换为字符串 return new String(out, "UTF-8"); } catch (Exception e) { e.printStackTrace(); return null; } } } ``` 使用示例: ```java public class SM4Test { public static void main(String[] args) { String key = "0123456789abcdef0123456789abcdef"; // 16字节密钥 String data = "hello world!"; String encrypted = SM4Util.encryptECB(key, data); String decrypted = SM4Util.decryptECB(key, encrypted); System.out.println("加密前:" + data); System.out.println("加密后:" + encrypted); System.out.println("解密后:" + decrypted); } } ``` 需要注意的是,以上代码使用了Bouncy Castle库提供的SM4实现。在使用之前需要先添加Bouncy Castle的依赖。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值