java从国密或RAS证书读取base64和16进制公钥

话不多说,直接上代码,逻辑挺简单的 

依赖pom文件

org.bouncycastle

bcprov-jdk15on

1.65

compile

RSA的


import org.bouncycastle.util.encoders.Base64;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.security.PublicKey;

import java.security.cert.CertificateException;

import java.security.cert.CertificateFactory;

import java.security.cert.X509Certificate;

public class testRSA{

public static void main(String[] args) {

String filePath ="E:\\sc银行yhtest01.cer";

String key ="";

try {

CertificateFactory cf = CertificateFactory.getInstance("X.509");

FileInputStream in =new FileInputStream(filePath);//生成一个证书对象并使用从输入流 inStream 中读取的数据对它进行初始化。

X509Certificate cert = (X509Certificate) cf.generateCertificate(in);

PublicKey publicKey = cert.getPublicKey();

key = Base64.toBase64String(publicKey.getEncoded());

System.out.println("base64公钥:" + key);

}catch (CertificateException e) {

e.printStackTrace();

}catch (FileNotFoundException e) {

e.printStackTrace();

}

}

}

国密的


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import org.bouncycastle.util.encoders.Base64;

import java.io.FileInputStream;

import java.io.IOException;

import java.security.NoSuchProviderException;

import java.security.PublicKey;

import java.security.Security;

import java.security.cert.CertificateException;

import java.security.cert.CertificateFactory;

import java.security.cert.X509Certificate;

public class testSM2 {

public static void main(String[] args)throws CertificateException, NoSuchProviderException, IOException {

String cerPath ="E:\\[email protected]";

X509Certificate x509Certificate =null;

//国密证书使用了自有的椭圆曲线,无法使用JDK自带的java.security解析证书,需要引入BouncyCastle的BC库支持国密算法

        Security.addProvider(new BouncyCastleProvider());//bcprov-jdk15on需1.59以上的版本

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");

FileInputStream fileInputStream =new FileInputStream(cerPath);

x509Certificate = (X509Certificate) certificateFactory.generateCertificate(fileInputStream);

fileInputStream.close();

PublicKey publicKey = x509Certificate.getPublicKey();

String key = Base64.toBase64String(publicKey.getEncoded());

byte[] bytes = publicKey.getEncoded();

String publicKeyHex =bytesToHex(bytes);

System.out.println("base64公钥:" + key);

System.out.println("16进制公钥:" + publicKeyHex);

}

//将publickey数组转成16进制字符串

public static String bytesToHex(byte[] bytes) {

StringBuffer sb =new StringBuffer();

for (int i =0; i < bytes.length; i++) {

String hex = Integer.toHexString(bytes[i] &0xFF);

if (hex.length() <2) {

sb.append(0);

}

sb.append(hex);

}

return sb.toString();

}

}

你可能感兴趣的:(java从国密或RAS证书读取base64和16进制公钥)