import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Base64;
public class Sm4EcbUtils {
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final String ALGORITHM = "SM4/ECB/PKCS5Padding";
private static final String TRANSFORMATION = "SM4";
/**
* SM4 ECB模式加密
* @param key 密钥,必须是16字节
* @param data 明文数据
* @return 密文,Base64编码
* @throws RuntimeException 包含可能的加密异常
*/
public static String encrypt(byte[] key, String data) throws RuntimeException {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
SecretKeySpec sm4Key = new SecretKeySpec(key, TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, sm4Key);
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException("Encryption failed: " + e.getMessage(), e);
}
}
/**
* SM4 ECB模式解密
* @param key 密钥,必须是16字节
* @param base64EncryptedData Base64编码的密文数据
* @return 解密后的明文数据
* @throws RuntimeException 包含可能的解密异常
*/
public static String decrypt(byte[] key, String base64EncryptedData) throws RuntimeException {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
SecretKeySpec sm4Key = new SecretKeySpec(key, TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, sm4Key);
byte[] encryptedBytes = Base64.getDecoder().decode(base64EncryptedData);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException("Decryption failed: " + e.getMessage(), e);
}
}
}
05-21
8415
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-15
9897
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-15
6198
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-19
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交