前端传来一个SM2加密后的密码,后端用SM2私钥解密,java
时间: 2024-06-11 19:05:21 浏览: 187
实现如下:
1.首先,需要引入BouncyCastle库,这是一个密码学库,用于支持SM2算法。
```java
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import java.security.Security;
```
2.使用BouncyCastleProvider提供者进行初始化。
```java
Security.addProvider(new BouncyCastleProvider());
```
3.获取SM2私钥和加密的密码。
```java
String privateKeyStr = "私钥字符串";
String encryptedPassword = "加密后的密码字符串";
```
4.将私钥转化为ECPrivateKeyParameters类型。
```java
byte[] privateKeyBytes = Base64.decode(privateKeyStr);
ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) PrivateKeyFactory.createKey(privateKeyBytes);
```
5.将加密的密码转化为byte数组。
```java
byte[] encryptedPasswordBytes = Base64.decode(encryptedPassword);
```
6.使用SM2算法进行解密。
```java
SM2Engine engine = new SM2Engine();
CipherParameters param = new ParametersWithRandom(privateKey);
engine.init(false, param);
byte[] decryptedPasswordBytes = engine.processBlock(encryptedPasswordBytes, 0, encryptedPasswordBytes.length);
```
7.将解密后的密码转化为字符串。
```java
String decryptedPassword = new String(decryptedPasswordBytes);
```
完整代码实现:
```java
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import java.security.Security;
public class SM2Util {
public static void main(String[] args) {
Security.addProvider(new BouncyCastleProvider());
String privateKeyStr = "私钥字符串";
String encryptedPassword = "加密后的密码字符串";
try {
byte[] privateKeyBytes = Base64.decode(privateKeyStr);
ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) PrivateKeyFactory.createKey(privateKeyBytes);
byte[] encryptedPasswordBytes = Base64.decode(encryptedPassword);
SM2Engine engine = new SM2Engine();
CipherParameters param = new ParametersWithRandom(privateKey);
engine.init(false, param);
byte[] decryptedPasswordBytes = engine.processBlock(encryptedPasswordBytes, 0, encryptedPasswordBytes.length);
String decryptedPassword = new String(decryptedPasswordBytes);
System.out.println(decryptedPassword);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文