用java实现SM4算法
时间: 2024-12-12 12:13:23 浏览: 10
在Java中实现SM4算法,你需要依赖于一些专门库,如Bouncy Castle Crypto或JSSE(Java Secure Socket Extension)。以下是使用Bouncy Castle库的一个简单示例:
```java
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.util.Base64;
public class SM4Example {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "SM4");
Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding", "BC");
byte[] iv = "0123456789ABCDEF".getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "SM4");
Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding", "BC");
byte[] iv = "0123456789ABCDEF".getBytes();
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedData);
}
public static void main(String[] args) throws Exception {
// 示例加密和解密
String message = "Hello, SM4!";
String key = "0123456789abcdef";
String encrypted = encrypt(message, key);
String decrypted = decrypt(encrypted, key);
System.out.println("Original: " + message);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
}
}
```
这个例子展示了如何创建一个SM4密钥,设置初始向量,以及执行加密和解密操作。记得替换实际的key和message进行测试。
阅读全文