java实现sm4加解密
时间: 2023-10-05 07:05:53 浏览: 64
你可以使用Java Cryptographic Extension (JCE)来实现SM4加解密。以下是一个简单的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class SM4EncryptionDemo {
public static void main(String[] args) throws Exception {
String plaintext = "Hello, world!";
String key = "0123456789abcdef";
// 加密
byte[] ciphertext = encrypt(plaintext, key);
System.out.println("Ciphertext: " + Base64.getEncoder().encodeToString(ciphertext));
// 解密
String decryptedText = decrypt(ciphertext, key);
System.out.println("Decrypted text: " + decryptedText);
}
public static byte[] encrypt(String plaintext, String key) throws Exception {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "SM4");
Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] plaintextBytes = plaintext.getBytes(StandardCharsets.UTF_8);
byte[] ciphertext = cipher.doFinal(plaintextBytes);
return ciphertext;
}
public static String decrypt(byte[] ciphertext, String key) throws Exception {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "SM4");
Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decryptedBytes = cipher.doFinal(ciphertext);
String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
return decryptedText;
}
}
```
请注意,此示例代码使用的SM4实现来自Bouncy Castle库。您需要将Bouncy Castle库添加到您的项目中。可以通过在Maven项目的pom.xml文件中添加以下依赖项来完成此操作:
```xml
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15to18</artifactId>
<version>1.70</version>
</dependency>
```
这只是一个基本示例,实际应用中可能需要更多的安全措施和错误处理。