sm2加签验签demo
时间: 2023-07-23 07:55:45 浏览: 106
sm2sm4加解密加签验签demo
以下是 sm2 加签验签的示例代码,使用了 Bouncy Castle 库:
```java
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import java.security.*;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
public class SM2Demo {
public static void main(String[] args) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException, InvalidKeyException, SignatureException, CryptoException {
Security.addProvider(new BouncyCastleProvider());
// 生成密钥对
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "BC");
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("sm2p256v1");
kpg.initialize(ecSpec, new SecureRandom());
KeyPair keyPair = kpg.generateKeyPair();
// 待签名数据
String data = "Hello, world!";
byte[] dataBytes = data.getBytes();
// 生成签名
SM2Signer signer = new SM2Signer();
signer.init(true, keyPair.getPrivate());
signer.update(dataBytes, 0, dataBytes.length);
byte[] signature = signer.generateSignature();
// 验证签名
signer.init(false, keyPair.getPublic());
signer.update(dataBytes, 0, dataBytes.length);
boolean verified = signer.verifySignature(signature);
System.out.println("Signature: " + Hex.toHexString(signature));
System.out.println("Verified: " + verified);
}
}
```
注意:需要先添加 Bouncy Castle 作为安全提供者。在示例代码中,我们使用了 SM2Signer 类来进行加签和验签操作,使用了 ECNamedCurveTable 类来获取 SM2 的椭圆曲线参数。在实际应用中,密钥对的生成应该是在安全的环境下进行,而不是在代码中直接生成。
阅读全文