项目需求要用SM4加密,搜了搜用的多,但有用的少,记录一下。
添加依赖:
implementation 'cn.hutool:hutool-all:5.4.5'
然后再下载这个jar包到本地,引入
https://download.csdn.net/download/wuqingsen1/86823072
implementation files('libs/bcprov-jdk15on-1.65.01.jar')
或者,添加依赖,但我一直失败:
implementation 'org.bouncycastle:bcprov-jdk15on:1.58'
工具类:
package com.sinosoft.cs.utils.common;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
/**
* wuqingsen on 10/25/22
* Mailbox:807926618@qq.com
* annotation:
*/
public class sm4Demo {
//key必须是16字节,即128位
final static String key = "JeF8U9wHFOMfs2Y8";
//指明加密算法和秘钥
static SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", key.getBytes());
//加密为16进制,也可以加密成base64/字节数组
public static String encrypt16Sm4(String plaintext) {
return sm4.encryptBase64(plaintext);
}
//加密为base64/字节数组
public static String encrypt64Sm4(String plaintext) {
return sm4.encryptBase64(plaintext);
}
//解密
public static String decrypt16Sm4(String ciphertext) {
return sm4.decryptStr(ciphertext);
}
}
可以加密为16进制或base64,按个人需求。
使用:
sm4Demo.encrypt64Sm4("{\"salesNo\":\"123\",\"time\":123}");
java中的url进行编码和解码:
URLEncoder.encode(a, "UTF-8");