sm4加密算法java代码
时间: 2024-07-30 22:00:18 浏览: 61
SM4(Stream cipher Mode with 4 keys)是一种中国自主研发的块密码,它属于SM系列,主要用于对数据流进行加密。在Java中,如果你想要使用SM4加密算法,你需要依赖于一些第三方库,如BCryptor或JSSE(Java Security Extension),因为Java标准库本身并未直接提供SM4的支持。
以下是一个简单的使用BCryptor库实现SM4加密的例子:
```java
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class SM4Example {
static {
// 注册BouncyCastle Provider
try {
Security.addProvider(new BouncyCastleProvider());
} catch (Exception e) {
e.printStackTrace();
}
}
private static final String SM4_ALGORITHM = "AES/SM4/NoPadding";
public static String encrypt(String key, String iv, String plainText) {
try {
byte[] keyBytes = key.getBytes("UTF-8");
byte[] ivBytes = iv.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance(SM4_ALGORITHM, "BC");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(ivBytes));
byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
return bytesToHex(encrypted);
} catch (Exception e) {
throw new RuntimeException("Failed to encrypt", e);
}
}
private static String decrypt(String key, String iv, String cipherText) {
// 解密过程类似,只是cipher.init()中的Cipher.ENCRYPT_MODE改为Cipher.DECRYPT_MODE
// 并用相同的key和iv
// ...
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
hex.append(String.format("%02x", b));
}
return hex.toString();
}
// 使用示例
public static void main(String[] args) {
String key = "your_secret_key";
String iv = "your_initialization_vector";
String plainText = "Hello, World!";
String encrypted = encrypt(key, iv, plainText);
System.out.println("Encrypted: " + encrypted);
// 更多处理...
}
}
```
阅读全文