版本:jdk1.8
Maven依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.4</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.66</version>
</dependency>
版本:jdk1.7
Maven依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.17</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.63</version>
</dependency>
代码示例:
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import java.nio.charset.StandardCharsets;
public class Main {
/**
* 加密
*
* @param msg
* @return
*/
public static String encrypt(String key,String msg) {
SymmetricCrypto sm4 = SmUtil.sm4(key.getBytes(StandardCharsets.UTF_8));
//加密
String encryptHex = sm4.encryptHex(msg);
return encryptHex;
}
/**
* 解密
* @param key
* @param msg
* @return
*/
public static String dencrypt(String key,String msg){
SymmetricCrypto sm4 = SmUtil.sm4(key.getBytes(StandardCharsets.UTF_8));
//解密
String decryptStr = sm4.decryptStr(msg, CharsetUtil.CHARSET_UTF_8);
return decryptStr;
}
public static void main(String[] args) {
// key必须是16位
String key="1234567890123456";
String name = "fisco bcos";
name = Main.encrypt(key,name);
System.out.println(name);
System.out.println(Main.dencrypt(key,name));
}
}
控制台输出: