java如何读取sm2的pem文件获取公钥,并获取base64编码的公钥
时间: 2024-01-26 17:05:00 浏览: 156
openssl SM2 密钥解析出公钥和私钥
要读取SM2的PEM格式文件并获取公钥,可以使用Bouncy Castle库中的SM2PublicKey类。
以下是Java代码示例:
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.Security;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
import org.bouncycastle.crypto.util.PrivateKeyInfoParser;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoParser;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
public class SM2PublicKeyReader {
public static void main(String[] args) throws Exception {
// 添加Bouncy Castle提供程序
Security.addProvider(new BouncyCastleProvider());
// 读取PEM文件
String pemFile = "sm2_public_key.pem";
BufferedReader reader = new BufferedReader(new FileReader(pemFile));
PemReader pemReader = new PemReader(reader);
PemObject pemObject = pemReader.readPemObject();
byte[] pemContent = pemObject.getContent();
// 解析SubjectPublicKeyInfo
SubjectPublicKeyInfoParser subjectPublicKeyInfoParser = new SubjectPublicKeyInfoParser(pemContent);
ECPublicKeyParameters ecPublicKeyParameters = (ECPublicKeyParameters) PublicKeyFactory.createKey(subjectPublicKeyInfoParser.getSubjectPublicKeyInfo());
// 获取公钥
byte[] publicKeyBytes = ecPublicKeyParameters.getQ().getEncoded(true);
String publicKeyBase64 = java.util.Base64.getEncoder().encodeToString(publicKeyBytes);
System.out.println("Public key in base64: " + publicKeyBase64);
}
}
```
这个示例代码假设PEM文件中只包含一个SM2公钥。如果PEM文件中包含多个公钥或私钥,则需要根据具体情况进行调整。
阅读全文