JojoMiss

疯魔jojo的后花园

导航

SM4加密

org.bouncycastle.jce.provider.BouncyCastleProvider;
org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
javax.crypto.Cipher;
javax.crypto.spec.SecretKeySpec;
java.security.Key;
java.security.Security;
/*入参:
str:
EPIDEMIC_KEY
*/
String ENCODING = "UTF-8";
String ALGORITHM_NAME = "SM4";
String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
Security.addProvider(new BouncyCastleProvider());
try {
    if (str != null && !"".equals(str)) {
        String cipherText = "";
        // 16进制字符串-->byte[]
        byte[] keyData = ByteUtils.fromHexString(EPIDEMIC_KEY);
        // String-->byte[]
        byte[] srcData = str.getBytes(ENCODING);
        // 加密后的数组
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(keyData, ALGORITHM_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, sm4Key);
        byte[] cipherArray = cipher.doFinal(srcData);
        // byte[]-->hexString
        cipherText = ByteUtils.toHexString(cipherArray);
        System.out.println("cipherText:" + cipherText);
        return cipherText;
    } else {
        return str;
    }
} catch (Exception e) {
    return str;
}

 

posted on 2024-04-01 13:22  幽忧一世  阅读(15)  评论(0编辑  收藏  举报

⭐️CSDN 我的文章列表⭐️
⭐WEIBO 微博首页⭐️
⭐园子 我的院子⭐️