vue
引入的包
npm install sm-crypto
代码加密解密
加密:
key :代表着密钥,必须是16 字节的十六进制密钥
password :加密前的密码
sm4Password :代表sm4加密后的密文
const sm4 = require('sm-crypto').sm4
const key = '0123456789abcdeffedcba9876543210' // 16 字节的十六进制密钥
const sm4Password = sm4.encrypt(password, key)
解密:
key :代表着密钥,必须是16 字节的十六进制密钥
sm4Password:解密前的密文
password:解密后的密码
const sm4 = require('sm-crypto').sm4
const key = '0123456789abcdeffedcba9876543210' // 16 字节的十六进制密钥
const password= sm4.decrypt(sm4Password , key)
java
maven
<!--sm4-->
<dependency>
<groupId>***.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.22</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version> <!-- 使用最新版本 -->
</dependency>
代码
加密和解密:
import ***.hutool.crypto.symmetric.Symmetri***rypto;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import java.security.Security;
public class SM4DecryptionExample {
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;
public static void main(String arg[]) throws Exception {
String paramStr = "pass$123";
String key = "0123456789abcdeffedcba9876543210";
String arfter = encrypt(key,paramStr);
String brfore = decrypt(key,arfter);
System.out.println("明文:---------------------"+paramStr);
System.out.println("加密后密文:---------------------"+arfter);
System.out.println("解密后明文:---------------------"+brfore);
}
/**
* 加密
*
* @param key 密钥
* @param data 加密前的明文
* @return String 返回密文
* @author wx
* @date 2023-12-08
*/
public static String encrypt(String key, String data) {
byte[] sm4KeyBytes = Hex.decode(key);
Symmetri***rypto sm4 = new Symmetri***rypto("SM4/ECB/PKCS5Padding", sm4KeyBytes);
return sm4.encryptHex(data).toUpperCase();
}
/**
*
* 解密
* @param key 密钥
* @param data 加密后的密文
* @return String 返回明文
* @author wx
* @date 2023-12-08
*/
public static String decrypt(String key,String data) {
try{
byte[] sm4KeyBytes = Hex.decode(key);
Symmetri***rypto sm4 = new Symmetri***rypto("SM4/ECB/PKCS5Padding", sm4KeyBytes);
return sm4.decryptStr(data);
}catch (Exception e){
return data;
}
}
}