java使用SM4使用ECB模式加密
时间: 2024-02-21 12:54:26 浏览: 223
Sm4Utils.rar_SM4加密_nation4l3_sm4_sm4 cbc java实例_sm4cbc和ECB
以下是Java使用SM4算法ECB模式加密的示例代码:
```java
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;
public class SM4Util {
private static final String ALGORITHM_NAME = "SM4";
private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS7Padding";
/**
* SM4加密
*
* @param key 16位秘钥
* @param data 待加密数据
* @return 加密结果
* @throws Exception
*/
public static String encryptData_ECB(String key, String data) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, "BC");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM_NAME);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encrypted);
}
/**
* SM4解密
*
* @param key 16位秘钥
* @param cipherText 待解密数据
* @return 解密结果
* @throws Exception
*/
public static String decryptData_ECB(String key, String cipherText) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, "BC");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM_NAME);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(decrypted, "UTF-8");
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) throws Exception {
String key = "1234567890abcdef";
String data = "hello world";
String encryptedData = SM4Util.encryptData_ECB(key, data);
System.out.println("加密后的数据:" + encryptedData); String decryptedData = SM4Util.decryptData_ECB(key, encryptedData);
System.out.println("解密后的数据:" + decryptedData);
}
}
```
阅读全文