123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package com.caimei.modules.order.utils;
- import org.bouncycastle.jce.provider.BouncyCastleProvider;
- import java.io.ByteArrayInputStream;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.security.*;
- import java.security.cert.CertificateException;
- import java.security.cert.CertificateFactory;
- import java.security.cert.X509Certificate;
- import java.util.Enumeration;
- /**
- * 合利宝证书工具类
- */
- public abstract class HeliPayCertUtils {
- private HeliPayCertUtils() {}
- public static PublicKey getPublicKey(String certFilePath) throws CertificateException, IOException, NoSuchProviderException {
- return getX509Certificate(certFilePath).getPublicKey();
- }
- /**
- * 获取证书
- * @param certFilePath
- * @return
- * @throws CertificateException
- * @throws NoSuchProviderException
- * @throws IOException
- */
- public static X509Certificate getX509Certificate(String certFilePath) throws CertificateException,
- NoSuchProviderException, IOException {
- CertificateFactory cf = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
- byte[] readAllBytes = Files.readAllBytes(Paths.get(certFilePath));
- String fileContent = new String(readAllBytes);
- if("-----BEGIN CERTIFICATE-----".indexOf(fileContent) < 0){
- fileContent = "-----BEGIN CERTIFICATE-----\n" + fileContent +
- "\n-----END CERTIFICATE-----";
- }
- InputStream is = new ByteArrayInputStream(fileContent.getBytes());
- return (X509Certificate) cf.generateCertificate(is);
- }
- public static PrivateKey getPrivateKeyByPfx(String pfxPath, String pfxPassword) {
- try {
- KeyStore ks = KeyStore.getInstance("PKCS12",getProvider());
- FileInputStream fis = new FileInputStream(pfxPath);
- // If the keystore password is empty(""), then we have to set
- // to null, otherwise it won't work!!!
- char[] nPassword = null;
- if ((pfxPassword == null) || pfxPassword.trim().equals("")) {
- nPassword = null;
- } else {
- nPassword = pfxPassword.toCharArray();
- }
- ks.load(fis, nPassword);
- fis.close();
- Enumeration enumas = ks.aliases();
- String keyAlias = null;
- if (enumas.hasMoreElements())// we are readin just one certificate.
- {
- keyAlias = (String) enumas.nextElement();
- }
- PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);
- return prikey;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- private static Provider getProvider() {
- return Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
- }
- }
|