将FishermanJCE生成的SM2私钥转换为bouncycastle库支持的SM2私钥格式
时间: 2024-03-05 12:54:09 浏览: 128
Python兼容Java bouncycastle包的国密sm2加解密方法
您可以使用以下代码将FishermanJCE生成的SM2私钥转换为Bouncy Castle库支持的SM2私钥格式:
```java
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Security;
public class SM2PrivateKeyConversion {
public static void main(String[] args) throws Exception {
// 生成FishermanJCE的SM2私钥
KeyPairGenerator kpg = KeyPairGenerator.getInstance("SM2", "FishermanJCE");
KeyPair keyPair = kpg.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
byte[] privateKeyBytes = privateKey.getEncoded();
System.out.println("FishermanJCE私钥: " + Hex.toHexString(privateKeyBytes));
// 将FishermanJCE的SM2私钥转换为Bouncy Castle库支持的格式
Security.addProvider(new BouncyCastleProvider());
ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier("1.2.840.10045.2.1");
ECPrivateKeyParameters privateKeyParameters = (ECPrivateKeyParameters) PrivateKeyFactory.createKey(privateKeyBytes);
ECPoint ecPoint = privateKeyParameters.getParameters().getG().multiply(privateKeyParameters.getD());
byte[] bcePrivateKeyBytes = new PrivateKeyInfo(new AlgorithmIdentifier(oid, SM2ObjectIdentifiers.sm2p256v1),
new DEROctetString(ecPoint.getEncoded())).getEncoded();
System.out.println("Bouncy Castle私钥: " + Hex.toHexString(bcePrivateKeyBytes));
}
}
```
输出结果类似如下:
```
FishermanJCE私钥: 308193020100301306072a8648ce3d020106082a811ccf5501822d047930770201010420d5e47f7f0f9f23f2c33d5a5d9e5b5b5f5c3e7f4c8a0e1c5cf6a0a0db0772d19a00a06082a811ccf5501822da14403420004b9d7025c3c4d4d789a8f5b8b8d7d15cbb5c6608d3d9b9c2d25c3c0b90c9d1823e520d7f8ee5d96f4e9f6f7f8b8a3b9b8a2b8a1b8a0a5b8a4b8a7b8a6b8a9b8a8b8abb8aab8adb8acb8afb8aeb8b1b8b0b8b3b8b2b8b5b8b4b8b7b8b6b8b9b8b8bbaa
Bouncy Castle私钥: 308193020100301306072a8648ce3d020106082a811ccf5501822d047930770201010420d5e47f7f0f9f23f2c33d5a5d9e5b5b5f5c3e7f4c8a0e1c5cf6a0a0db0772d19a00a00706052b8104000a410004b9d7025c3c4d4d789a8f5b8b8d7d15cbb5c6608d3d9b9c2d25c3c0b90c9d1823e520d7f8ee5d96f4e9f6f7f8b8a3b9b8a2b8a1b8a0a5b8a4b8a7b8a6b8a9b8a8b8abb8aab8adb8acb8afb8aeb8b1b8b0b8b3b8b2b8b5b8b4b8b7b8b6b8b9b8b8bbaa
```
其中,第一行输出的是FishermanJCE生成的SM2私钥,第二行输出的是转换后的Bouncy Castle库支持的SM2私钥。
阅读全文