java sm2加密
时间: 2023-10-04 07:13:17 浏览: 201
Java中实现SM2加密需要使用Bouncy Castle库。以下是一个示例代码:
```java
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import java.security.KeyPair;
import java.security.Security;
public class SM2EncryptionExample {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// 生成SM2密钥对
KeyPair keyPair = generateKeyPair();
byte[] plaintext = "Hello, SM2".getBytes();
byte[] ciphertext = encrypt(plaintext, keyPair.getPublic());
System.out.println("密文: " + new String(ciphertext));
byte[] decryptedText = decrypt(ciphertext, keyPair.getPrivate());
System.out.println("解密后的明文: " + new String(decryptedText));
}
// 生成SM2密钥对
public static KeyPair generateKeyPair() {
try {
ECNamedCurveParameterSpec spec = ECNamedCurveParameterSpec.getByName("sm2p256v1");
ECDomainParameters ecParams = new ECDomainParameters(spec.getCurve(), spec.getG(), spec.getN());
ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(ecParams, null);
ECKeyPairGenerator generator = new ECKeyPairGenerator();
generator.init(keyGenParams);
AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate();
ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic();
return new KeyPair(new BCECPrivateKey(privateKey), new BCECPublicKey(publicKey));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 使用公钥进行加密
public static byte[] encrypt(byte[] plaintext, java.security.PublicKey publicKey) {
try {
SM2Engine engine = new SM2Engine();
engine.init(true, new ParametersWithRandom(publicKey, new SecureRandom()));
return engine.processBlock(plaintext, 0, plaintext.length);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 使用私钥进行解密
public static byte[] decrypt(byte[] ciphertext, java.security.PrivateKey privateKey) {
try {
SM2Engine engine = new SM2Engine();
engine.init(false, privateKey);
return engine.processBlock(ciphertext, 0, ciphertext.length);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
请注意,这里使用了Bouncy Castle库提供的SM2引擎进行加密和解密操作。你需要将Bouncy Castle库添加到你的项目中,以便能够使用相关的类和方法。
阅读全文