前端VUE后端JAVA,SM2加解密,一篇解决你的问题
在Vue前端和Java后端之间进行SM2加解密,你可以使用第三方库来简化这个过程。以下是一个使用sm-crypto
库在Vue前端和Java后端进行SM2加解密的示例。
前端(Vue):
首先,需要安装sm-crypto
库:
npm install sm-crypto --save
然后,你可以使用如下方式进行加密和解密:
import sm2 from 'sm-crypto').sm2;
// 假设你有一个公钥和私钥
const publicKey = '你的公钥';
const privateKey = '你的私钥';
// 需要加密的数据
const data = '需要加密的数据';
// 加密
const encryptedData = sm2.doEncrypt(data, publicKey);
// 解密
const decryptedData = sm2.doDecrypt(encryptedData, privateKey);
后端(Java):
在Java中,你可以使用BouncyCastle
库来进行SM2加解密。首先,需要添加BouncyCastle依赖到你的项目中。
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.68</version>
</dependency>
然后,你可以使用如下方式进行加密和解密:
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.jce.interfaces.ECPrivateKey;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import java.security.KeyFactory;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class SM2Utils {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static String encrypt(String publicKey, String data) throws Exception {
// 转换公钥格式
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
ECPublicKey ecPublicKey = (ECPublicKey) keyFactory.generatePublic(x509En
评论已关闭