Java 和 Vue 前后端实现国密SM2 API接口加密
在Java后端使用Bouncy Castle库实现SM2加密,并在Vue前端进行调用和展示。
后端Java代码示例:
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.modes.GMTEncryptingState;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECPoint;
import java.security.KeyFactory;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class SM2Encryption {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static String generateKeyPair() {
ECKeyPairGenerator keyGenerator = new ECKeyPairGenerator();
keyGenerator.init(new ECKeyPairGenerator.ECKeyGenerationParameters(
ECDomainParameters.sm2p256v1,
new SecureRandom()
));
AsymmetricCipherKeyPair keyPair = keyGenerator.generateKeyPair();
ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate();
ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic();
// 私钥
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
java.security.PrivateKey privateKeyJava = keyFactory.generatePrivate(privateKeySpec);
// 公钥
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey.getQ().getEncoded(false));
java.security.PublicKey publicKeyJava = keyFactory.generatePublic(publicKeySpec);
// 将私钥和公钥转换为Base64以便传输
String privateKeyStr = Base64.getEncoder().encodeToString(privateKeyJava.getEncoded());
String publicKeyStr = Base64.getEncoder().encodeToStr
评论已关闭