sm2 前端加密 后端java解密代码
时间: 2023-08-09 19:07:28 浏览: 162
下面是一个简单的前端使用 sm2 加密,后端使用 java 解密的示例代码:
前端代码:
```javascript
import { sm2 } from "sm-crypto";
// 待加密的数据
const data = "Hello, World!";
// 公钥
const publicKey = "04a0b5376a5deca1c8dbf9c3d9f7f82d7d3a96fc79a2f54b6a4e55d90d5e9a7d2ee1d1c1b9ea37a7c3ddafef5e6d67f3dcd91f4e6c8aa1a5c5d7d4e38bda9c02e";
// 将公钥转换为 sm2 公钥对象
const publicKeyObj = sm2.SM2KeyPair(publicKey, "", {
curve: "sm2p256v1",
publicKeyType: "uncompressed",
});
// 使用 sm2 加密数据,并将加密结果进行 base64 编码
const encryptedData = sm2.doEncrypt(data, publicKeyObj).toString("base64");
// 将加密结果发送给后端
```
后端代码:
```java
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ParametersWithID;
import org.bouncycastle.crypto.params.SM2KeyExchangePrivateParameters;
import org.bouncycastle.crypto.params.SM2KeyExchangePublicParameters;
import org.bouncycastle.crypto.params.SM2PrivateKeyParameters;
import org.bouncycastle.crypto.params.SM2PublicKeyParameters;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;
public class SM2Demo {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// 私钥,从配置文件或数据库中读取
String privateKeyStr = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
// 将私钥转换为 sm2 私钥对象
byte[] privateKeyBytes = Hex.decode(privateKeyStr);
SM2PrivateKeyParameters privateKey = new SM2PrivateKeyParameters(privateKeyBytes, SM2Util.DOMAIN_PARAMS);
// 加密后的数据,从前端接收
String encryptedDataStr = "QXZlbnQgUGF5bG9hZA==";
byte[] encryptedData = Base64.decode(encryptedDataStr);
// 使用 sm2 解密数据
SM2Engine engine = new SM2Engine();
engine.init(false, new ParametersWithID(null, null));
engine.processCiphertext(encryptedData, 0, encryptedData.length);
byte[] decryptedData = engine.doFinal();
// 输出解密结果
System.out.println(new String(decryptedData));
}
}
```
需要注意的是,在上面的示例代码中,我们使用了 BouncyCastle 提供的 sm2 实现。如果你使用的是其它实现,则代码可能会有所不同。
阅读全文