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;
}
标签:cipherText,加密,String,SM4,Cipher,str,byte,NAME From: https://www.cnblogs.com/JojoMiss/p/18108222