将字符串转换为X509Certificate对象.

@param x509CertString
@return
160659
public static X509Certificate genCertificateByStr(String x509CertString) {
		X509Certificate x509Cert = null;
		try {
			CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); 
			InputStream tIn = new ByteArrayInputStream(
					x509CertString.getBytes("ISO-8859-1"));
			x509Cert = (X509Certificate) cf.generateCertificate(tIn);
		} catch (Exception e) {
			LogUtil.writeErrorLog("gen certificate error", e);			
		}
		return x509Cert;
	}
696954
private static boolean verifyCertificateChain(X509Certificate cert){
		
		if ( null == cert) {
			LogUtil.writeErrorLog("cert must Not null");
			return false;
		}
		
		X509Certificate middleCert = CertUtil.getMiddleCert();
		if (null == middleCert) {
			LogUtil.writeErrorLog("middleCert must Not null");
			return false;
		}
		
		X509Certificate rootCert = CertUtil.getRootCert();
		if (null == rootCert) {
			LogUtil.writeErrorLog("rootCert or cert must Not null");
			return false;
		}
		
		try {
		
	        X509CertSelector selector = new X509CertSelector();
	        selector.setCertificate(cert);
	        
	        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
	        trustAnchors.add(new TrustAnchor(rootCert, null));
	        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(
			        trustAnchors, selector);
	
	        Set<X509Certificate> intermediateCerts = new HashSet<X509Certificate>();
	        intermediateCerts.add(rootCert);
	        intermediateCerts.add(middleCert);
	        intermediateCerts.add(cert);
	        
	        pkixParams.setRevocationEnabled(false);
	
	        CertStore intermediateCertStore = CertStore.getInstance("Collection",
	                new CollectionCertStoreParameters(intermediateCerts), "BC");
	        pkixParams.addCertStore(intermediateCertStore);
	
	        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
	        
        	@SuppressWarnings("unused")
			PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder
                .build(pkixParams);
			LogUtil.writeLog("verify certificate chain succeed.");
			return true;
        } catch (java.security.cert.CertPathBuilderException e){
			LogUtil.writeErrorLog("verify certificate chain fail.", e);
		} catch (Exception e) {
			LogUtil.writeErrorLog("verify certificate chain exception: ", e);
		}
		return false;
	}
603358
private X509Certificate[] getPeerCertificates() {
        X509Certificate[] rc = null;
        SSLContext ssl = this.connection.getSSLContext();
        if (null != ssl && (ssl.getNeedClientAuth() || ssl.getWantClientAuth())) {
            try {
                Object[] objs = ssl.getSession().getPeerCertificates();
                if (null != objs) {
                    rc = (X509Certificate[]) objs;
                }
            } catch (Throwable t) {
                FFDCFilter.processException(t,
                                            getClass().getName(), "peercerts",
                                            new Object[] { this, ssl });
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(tc, "Error getting peer certs; " + t);
                }
            }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            if (null == rc) {
                Tr.debug(tc, "getPeerCertificates: none");
            } else {
                Tr.debug(tc, "getPeerCertificates: " + rc.length);
            }
        }
        return rc;
    }
1266010
public static String getThumbprint(final X509Certificate cert) throws CertificateEncodingException {

		if(cert == null)
		{
			return null;
		}

		byte[] rawOctets = cert.getEncoded();

		SHA1Digest digest = new SHA1Digest();

		byte[] digestOctets = new byte[digest.getDigestSize()];

		digest.update(rawOctets, 0, rawOctets.length);

		digest.doFinal(digestOctets, 0);

		return new String(Base64.encode(digestOctets));
	}
178983
public static X509Certificate newClientCertificate(X509Metadata clientMetadata,
                                                       PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
        try {
            KeyPair pair = newKeyPair();

            X500Name userDN = buildDistinguishedName(clientMetadata);
            X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

            // create a new certificate signed by the Fathom CA certificate
            X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    clientMetadata.notBefore,
                    clientMetadata.notAfter,
                    userDN,
                    pair.getPublic());

            JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
            certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
            certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
            certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
            certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
            if (!Strings.isNullOrEmpty(clientMetadata.emailAddress)) {
                GeneralNames subjectAltName = new GeneralNames(
                        new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
                certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
            }

            ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);

            X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
            PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
            bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                    extUtils.createSubjectKeyIdentifier(pair.getPublic()));

            // confirm the validity of the user certificate
            userCert.checkValidity();
            userCert.verify(caCert.getPublicKey());
            userCert.getIssuerDN().equals(caCert.getSubjectDN());

            // verify user certificate chain
            verifyChain(userCert, caCert);

            targetFolder.mkdirs();

            // save certificate, stamped with unique name
            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String id = date;
            File certFile = new File(targetFolder, id + ".cer");
            int count = 0;
            while (certFile.exists()) {
                id = date + "_" + Character.toString((char) (0x61 + count));
                certFile = new File(targetFolder, id + ".cer");
                count++;
            }

            // save user private key, user certificate and CA certificate to a PKCS#12 store
            File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
            if (p12File.exists()) {
                p12File.delete();
            }
            KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
            userStore.setKeyEntry(MessageFormat.format("Fathom ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[]{userCert});
            userStore.setCertificateEntry(MessageFormat.format("Fathom ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
            saveKeyStore(p12File, userStore, clientMetadata.password);

            // save user private key, user certificate, and CA certificate to a PEM store
            File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
            if (pemFile.exists()) {
                pemFile.delete();
            }
            PEMWriter pemWriter = new PEMWriter(new FileWriter(pemFile));
            pemWriter.writeObject(pair.getPrivate(), "DES-EDE3-CBC", clientMetadata.password.toCharArray(), new SecureRandom());
            pemWriter.writeObject(userCert);
            pemWriter.writeObject(caCert);
            pemWriter.flush();
            pemWriter.close();

            // save certificate after successfully creating the key stores
            saveCertificate(userCert, certFile);

            // update serial number in metadata object
            clientMetadata.serialNumber = userCert.getSerialNumber().toString();

            return userCert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate client certificate!", t);
        }
    }
80467
private Collection<String> getCertServerNames(X509Certificate x509)
        throws CertificateParsingException {

        Collection<String> serverNames = new LinkedHashSet<>();

        /* Add CN for the certificate */
        String certCN = getCertCN(x509);
        serverNames.add(certCN);

        /* Add alternative names for each certificate */
        try {
            Collection<List<?>> altNames = x509.getSubjectAlternativeNames();
            if (altNames != null) {
                for (List<?> entry : altNames) {
                    if (entry.size() >= 2) {
                        Object entryType = entry.get(0);
                        if (entryType instanceof Integer &&
                            (Integer) entryType == 2) {

                            Object field = entry.get(1);
                            if (field instanceof String) {
                                serverNames.add(((String) field).toLowerCase());
                            }
                        }
                    }
                }
            }

        } catch (CertificateParsingException cpe) {
            LOGGER.warn("Certificate alternative names ignored for certificate " + (certCN != null ? " " + certCN : ""), cpe);
        }

        return serverNames;
    }
1069768
private String generateDigest(String algorithmName, X509Certificate cert) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithmName);
            md.update(cert.getEncoded());
            byte data[] = md.digest();

            StringBuilder buffer = new StringBuilder(3 * data.length);
            int i = 0;
            buffer.append(HEX_CHARS[(data[i] >> 4) & 0xF]);
            buffer.append(HEX_CHARS[(data[i] % 16) & 0xF]);
            for (++i; i < data.length; i++) {
                buffer.append(':');
                buffer.append(HEX_CHARS[(data[i] >> 4) & 0xF]);
                buffer.append(HEX_CHARS[(data[i] % 16) & 0xF]);
            }

            return buffer.toString();
        } catch (NoClassDefFoundError e) {
            return getMessage("sslTrust.genDigestError", algorithmName, e.getMessage());
        } catch (Exception e) {
            return getMessage("sslTrust.genDigestError", algorithmName, e.getMessage());
        }
    }
1020261
public X509CertificateHolder getCertificate(Selector selector)
    {
        try {
            return (X509CertificateHolder) this.store.getMatches(selector).iterator().next();
        } catch (Throwable t) {
            return null;
        }
    }
1317712
public static X500Principal getIssuerX500Principal(X509Certificate cert) {
        try {
            return getX500Principal(cert, true);
        } catch (Exception e) {
            throw new RuntimeException("Could not parse issuer", e);
        }
    }
1355178
public static java.security.cert.X509Certificate convert(javax.security.cert.X509Certificate cert) {
        try {
            byte[] encoded = cert.getEncoded();
            ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
            java.security.cert.CertificateFactory cf
                = java.security.cert.CertificateFactory.getInstance("X.509");
            return (java.security.cert.X509Certificate)cf.generateCertificate(bis);
        } catch (java.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateEncodingException e) {
        } catch (java.security.cert.CertificateException e) {
        }
        return null;
    }
1171538
public static PublicKey getValidatePublicKey(String certId) {
		X509Certificate cf = null;
		if (certMap.containsKey(certId)) {
			// 存在certId对应的证书对象
			cf = certMap.get(certId);
			return cf.getPublicKey();
		} else {
			// 不存在则重新Load证书文件目录
			initValidateCertFromDir();
			if (certMap.containsKey(certId)) {
				// 存在certId对应的证书对象
				cf = certMap.get(certId);
				return cf.getPublicKey();
			} else {
				LogUtil.writeErrorLog("缺少certId=[" + certId + "]对应的验签证书.");
				return null;
			}
		}
	}
28686
static public X509Certificate readCertificate(String filename)
            throws Exception {
        InputStream inStream = null;
        X509Certificate cert = null;
        try {
            inStream = Config.getInstance().getInputStreamFromFile(filename);
            if (inStream != null) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                cert = (X509Certificate) cf.generateCertificate(inStream);
            } else {
                logger.info("Certificate " + Encode.forJava(filename) + " not found.");
            }
        } catch (Exception e) {
            logger.error("Exception: ", e);
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException ioe) {
                    logger.error("Exception: ", ioe);
                }
            }
        }
        return cert;
    }
718656
private static String getCertIdIdByStore(KeyStore keyStore) {
		Enumeration<String> aliasenum = null;
		try {
			aliasenum = keyStore.aliases();
			String keyAlias = null;
			if (aliasenum.hasMoreElements()) {
				keyAlias = aliasenum.nextElement();
			}
			X509Certificate cert = (X509Certificate) keyStore
					.getCertificate(keyAlias);
			return cert.getSerialNumber().toString();
		} catch (KeyStoreException e) {
			LogUtil.writeErrorLog("getCertIdIdByStore Error", e);
			return null;
		}
	}
438680
@JsonIgnore
    public String getSigningCertificateDecoded() {
        if (EncodingUtils.isBase64(signingCertificate)) {
            return EncodingUtils.decodeBase64ToString(signingCertificate);
        }
        return signingCertificate;
    }
720408
public static String getCertIdByKeyStoreMap(String certPath, String certPwd) {
		if (!keyStoreMap.containsKey(certPath)) {
			// 缓存中未查询到,则加载RSA证书
			loadSignCert(certPath, certPwd);
		}
		return getCertIdIdByStore(keyStoreMap.get(certPath));
	}
1305317
public Sign setCertificate(Certificate certificate) {
		// If the certificate is of type X509Certificate,
		// we should check whether it has a Key Usage
		// extension marked as critical.
		if (certificate instanceof X509Certificate) {
			// Check whether the cert has a key usage extension
			// marked as a critical extension.
			// The OID for KeyUsage extension is 2.5.29.15.
			final X509Certificate cert = (X509Certificate) certificate;
			final Set<String> critSet = cert.getCriticalExtensionOIDs();

			if (CollUtil.isNotEmpty(critSet) && critSet.contains("2.5.29.15")) {
				final boolean[] keyUsageInfo = cert.getKeyUsage();
				// keyUsageInfo[0] is for digitalSignature.
				if ((keyUsageInfo != null) && (keyUsageInfo[0] == false)) {
					throw new CryptoException("Wrong key usage");
				}
			}
		}
		this.publicKey = certificate.getPublicKey();
		return this;
	}
60833
public static X509Certificate readCertificate(final InputStreamSource resource) {
        try (val in = resource.getInputStream()) {
            return CertUtil.readCertificate(in);
        } catch (final IOException e) {
            throw new IllegalArgumentException("Error reading certificate " + resource, e);
        }
    }