给我写一段SM2 加解密的java代码
时间: 2024-05-12 14:08:38 浏览: 10
好的,下面是一段简单的 SM2 加解密的 Java 代码:
```
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.*;
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.ECGenParameterSpec;
public class SM2Utils {
private static final int SM3_DIGEST_LENGTH = 32;
private static final String PROVIDER_NAME = "BC";
private static final SecureRandom RANDOM = new SecureRandom();
private static final X9ECParameters SM2_PARAMS = SECNamedCurves.getByName("sm2p256v1");
private static final int KEY_SIZE = 256;
private static final int SM3_KEY_LENGTH = 16;
private static final byte[] SM2_DEFAULT_ID = "1234567812345678".getBytes();
static {
if (Security.getProvider(PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
/**
* 生成 SM2 密钥对
*
* @return 返回 SM2 密钥对
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidAlgorithmParameterException
*/
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", PROVIDER_NAME);
ECGenParameterSpec ecSpec = new ECGenParameterSpec("sm2p256v1");
kpg.initialize(ecSpec, RANDOM);
return kpg.generateKeyPair();
}
/**
* SM2 加密
*
* @param publicKey 公钥
* @param data 待加密的数据
* @return 返回加密后的字节数组
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
*/
public static byte[] encrypt(PublicKey publicKey, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException, InvalidCipherTextException {
byte[] userId = SM2_DEFAULT_ID;
CipherParameters cp = new SM2KeyEncryptionParameters((SM2PublicKey) publicKey, userId);
SM2Engine engine = new SM2Engine();
engine.init(true, cp);
return engine.processBlock(data, 0, data.length);
}
/**
* SM2 解密
*
* @param privateKey 私钥
* @param cipherText 加密后的字节数组
* @return 返回解密后的字节数组
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
*/
public static byte[] decrypt(PrivateKey privateKey, byte[] cipherText) throws NoSuchAlgorithmException, InvalidKeyException, InvalidCipherTextException {
byte[] userId = SM2_DEFAULT_ID;
CipherParameters cp = new SM2KeyEncryptionParameters((SM2PrivateKey) privateKey, userId);
SM2Engine engine = new SM2Engine();
engine.init(false, cp);
return engine.processBlock(cipherText, 0, cipherText.length);
}
/**
* SM3 消息摘要
*
* @param data 待摘要的数据
* @return 返回摘要结果
* @throws NoSuchAlgorithmException
*/
public static byte[] sm3(byte[] data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SM3", PROVIDER_NAME);
return md.digest(data);
}
/**
* SM2 签名
*
* @param privateKey 私钥
* @param data 待签名的数据
* @return 返回签名后的字节数组
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static byte[] sign(PrivateKey privateKey, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException {
byte[] hash = sm3(data);
SM2Signer signer = new SM2Signer();
signer.init(true, new ECPrivateKeyParameters(((ECPrivateKey) privateKey).getS(), SM2_PARAMS));
signer.update(hash, 0, hash.length);
return signer.generateSignature();
}
/**
* SM2 验签
*
* @param publicKey 公钥
* @param data 待验签的数据
* @param signature 签名
* @return 返回验签结果
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static boolean verify(PublicKey publicKey, byte[] data, byte[] signature) throws NoSuchAlgorithmException, InvalidKeyException {
byte[] hash = sm3(data);
SM2Signer signer = new SM2Signer();
signer.init(false, new ECPublicKeyParameters(((ECPublicKey) publicKey).getQ(), SM2_PARAMS));
signer.update(hash, 0, hash.length);
return signer.verifySignature(signature);
}
public static void main(String[] args) {
try {
Security.addProvider(new BouncyCastleProvider());
KeyPair keyPair = generateKeyPair();
byte[] data = "Hello, world!".getBytes();
System.out.println("Encrypt data: " + Hex.toHexString(data));
byte[] cipherText = encrypt(keyPair.getPublic(), data);
System.out.println("Cipher text: " + Hex.toHexString(cipherText));
byte[] plainText = decrypt(keyPair.getPrivate(), cipherText);
System.out.println("Decrypted data: " + new String(plainText));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
希望能够帮到您!