下面列出了java.security.cert.PKIXRevocationChecker.Option#java.security.cert.CertPathValidator 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public SigningCertificate(String certificateChain, KeyStore trustStore)
throws CertificateException, CertPathValidatorException
{
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<X509Certificate> certificatesCollection = (Collection<X509Certificate>) certificateFactory.generateCertificates(new ByteArrayInputStream(certificateChain.getBytes()));
List<X509Certificate> certificates = new LinkedList<>(certificatesCollection);
PKIXParameters pkixParameters = new PKIXParameters(trustStore);
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
if (certificates.isEmpty()) {
throw new CertificateException("No certificates available! Badly-formatted cert chain?");
}
this.path = certificateFactory.generateCertPath(certificates);
pkixParameters.setRevocationEnabled(false);
validator.validate(path, pkixParameters);
verifyDistinguishedName(path);
} catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate, String hostName) throws CertificateException {
this.origTm = tm;
this.verifyServerCert = verifyServerCertificate;
this.hostName = hostName;
if (verifyServerCertificate) {
try {
Set<TrustAnchor> anch = Arrays.stream(tm.getAcceptedIssuers()).map(c -> new TrustAnchor(c, null)).collect(Collectors.toSet());
this.validatorParams = new PKIXParameters(anch);
this.validatorParams.setRevocationEnabled(false);
this.validator = CertPathValidator.getInstance("PKIX");
this.certFactory = CertificateFactory.getInstance("X.509");
} catch (Exception e) {
throw new CertificateException(e);
}
}
}
private static void runTest(CertificateFactory cf,
List<X509Certificate> certList, TrustAnchor anchor)
throws Exception {
CertPath path = cf.generateCertPath(certList);
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
System.out.println(anchor);
// Attach the OCSP responses to a PKIXParameters object
PKIXRevocationChecker pkrev =
(PKIXRevocationChecker)validator.getRevocationChecker();
Map<X509Certificate, byte[]> responseMap = new HashMap<>();
responseMap.put(certList.get(0), DECODER.decode(EE_OCSP_RESP));
responseMap.put(certList.get(1), DECODER.decode(INT_CA_OCSP_RESP));
pkrev.setOcspResponses(responseMap);
PKIXParameters params =
new PKIXParameters(Collections.singleton(anchor));
params.addCertPathChecker(pkrev);
params.setDate(EVAL_DATE);
validator.validate(path, params);
}
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException {
this.origTm = tm;
this.verifyServerCert = verifyServerCertificate;
if (verifyServerCertificate) {
try {
Set<TrustAnchor> anch = new HashSet<TrustAnchor>();
for (X509Certificate cert : tm.getAcceptedIssuers()) {
anch.add(new TrustAnchor(cert, null));
}
this.validatorParams = new PKIXParameters(anch);
this.validatorParams.setRevocationEnabled(false);
this.validator = CertPathValidator.getInstance("PKIX");
this.certFactory = CertificateFactory.getInstance("X.509");
} catch (Exception e) {
throw new CertificateException(e);
}
}
}
private void validateNoCache(List<? extends X509Certificate> certs)
throws SignatureException {
try {
CertPathValidator validator = CertPathValidator.getInstance(
VALIDATOR_TYPE);
PKIXParameters params = new PKIXParameters(trustRoots);
params.addCertPathChecker(WAVE_OID_CHECKER);
params.setDate(timeSource.now());
// turn off default revocation-checking mechanism
params.setRevocationEnabled(false);
// TODO: add a way for clients to add certificate revocation checks,
// perhaps by letting them pass in PKIXCertPathCheckers. This can also be
// useful to check for Wave-specific certificate extensions.
CertificateFactory certFactory = CertificateFactory.getInstance(
CERTIFICATE_TYPE);
CertPath certPath = certFactory.generateCertPath(certs);
validator.validate(certPath, params);
} catch (GeneralSecurityException e) {
throw new SignatureException("Certificate validation failure", e);
}
}
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException {
this.origTm = tm;
this.verifyServerCert = verifyServerCertificate;
if (verifyServerCertificate) {
try {
Set<TrustAnchor> anch = new HashSet<TrustAnchor>();
for (X509Certificate cert : tm.getAcceptedIssuers()) {
anch.add(new TrustAnchor(cert, null));
}
this.validatorParams = new PKIXParameters(anch);
this.validatorParams.setRevocationEnabled(false);
this.validator = CertPathValidator.getInstance("PKIX");
this.certFactory = CertificateFactory.getInstance("X.509");
} catch (Exception e) {
throw new CertificateException(e);
}
}
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
this.mOriginalX509TrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException e1) {
try {
X509Certificate[] ex = this.reorderCertificateChain(chain);
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
CertificateFactory factory = CertificateFactory.getInstance("X509");
CertPath certPath = factory.generateCertPath(Arrays.asList(ex));
PKIXParameters params = new PKIXParameters(this.mTrustStore);
params.setRevocationEnabled(false);
validator.validate(certPath, params);
} catch (Exception e) {
throw e1;
}
}
}
/**
* Check if a certificate chain is to be trusted.
*
* @return true, if validator trusts certificate chain, otherwise false.
*/
public boolean validateCertificateChain(List<X509Certificate> chain) {
if (keystore == null) {
return false;
}
try {
CertPath c = getCertificateFactory().generateCertPath(chain);
CertPathValidator cpv = getCertPathValidator();
CertPathParameters params = getCertPathParameters(keystore);
cpv.validate(c, params);
} catch (GeneralSecurityException gse) {
if (debug.certificates) {
debug.printStackTrace("Failed to validate cert", gse);
}
// NYI! Log this?
return false;
}
return true;
}
public SigningCertificate(String certificateChain, KeyStore trustStore)
throws CertificateException, CertPathValidatorException
{
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<X509Certificate> certificatesCollection = (Collection<X509Certificate>) certificateFactory.generateCertificates(new ByteArrayInputStream(URLDecoder.decode(certificateChain).getBytes()));
List<X509Certificate> certificates = new LinkedList<>(certificatesCollection);
PKIXParameters pkixParameters = new PKIXParameters(trustStore);
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
this.path = certificateFactory.generateCertPath(certificates);
pkixParameters.setRevocationEnabled(false);
validator.validate(path, pkixParameters);
verifyDistinguishedName(path);
} catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private void validateNoCache(List<? extends X509Certificate> certs)
throws SignatureException {
try {
CertPathValidator validator = CertPathValidator.getInstance(
VALIDATOR_TYPE);
PKIXParameters params = new PKIXParameters(trustRoots);
params.addCertPathChecker(WAVE_OID_CHECKER);
params.setDate(timeSource.now());
// turn off default revocation-checking mechanism
params.setRevocationEnabled(false);
// TODO: add a way for clients to add certificate revocation checks,
// perhaps by letting them pass in PKIXCertPathCheckers. This can also be
// useful to check for Wave-specific certificate extensions.
CertificateFactory certFactory = CertificateFactory.getInstance(
CERTIFICATE_TYPE);
CertPath certPath = certFactory.generateCertPath(certs);
validator.validate(certPath, params);
} catch (GeneralSecurityException e) {
throw new SignatureException("Certificate validation failure", e);
}
}
private static void validateCertificateChain(KeyStore ks, List<X509Certificate> inCerts, boolean enableRevocation) {
// Initial chain validation, to be enhanced as needed
try {
X509CertSelector certSelect = new X509CertSelector();
certSelect.setCertificate(inCerts.get(0));
PKIXBuilderParameters pbParams = new PKIXBuilderParameters(ks, certSelect);
pbParams.addCertStore(CertStore.getInstance("Collection",
new CollectionCertStoreParameters(inCerts)));
pbParams.setMaxPathLength(-1);
pbParams.setRevocationEnabled(false);
CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
pbParams.setRevocationEnabled(enableRevocation);
CertPath certPath = buildResult.getCertPath();
CertPathValidator.getInstance("PKIX").validate(certPath, pbParams);
} catch (Exception ex) {
LOG.warning("Certificate path validation error");
throw new JoseException(ex);
}
}
public static boolean pkixvalidate(CertPath cp, Set<TrustAnchor> trustAnchorSet,
boolean isRevocationChecked, boolean isPolicyQualifiersRejected) {
try {
CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); //TODO use BCFIPS when "Support for PKIXRevocationChecker
//in the CertPath implementation" is added
PKIXParameters pkix = new PKIXParameters(trustAnchorSet);
if(isRevocationChecked){
PKIXRevocationChecker prc = (PKIXRevocationChecker) cpv.getRevocationChecker();
prc.setOptions(EnumSet.of(PKIXRevocationChecker.Option.PREFER_CRLS, PKIXRevocationChecker.Option.NO_FALLBACK));
pkix.addCertPathChecker(prc);
}
else{
pkix.setRevocationEnabled(false);
}
pkix.setPolicyQualifiersRejected(isPolicyQualifiersRejected);
pkix.setDate(null);
CertPathValidatorResult cpvr = cpv.validate(cp, pkix);
if (cpvr != null) {
System.out.println("Certificate validated");
return true;
} else {
System.out.println("Certificate not valid");
return false;
}
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertPathValidatorException ex) {
Logger.getLogger(PKIXChainValidation.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
}
/**
* Constructor
*
* @param additionalTrustRoots trusted root certificates
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
*/
public ValidatePathWithParams(String[] additionalTrustRoots)
throws IOException, CertificateException, NoSuchAlgorithmException {
cf = CertificateFactory.getInstance("X509");
certPathValidator = CertPathValidator.getInstance("PKIX");
certPathChecker
= (PKIXRevocationChecker) certPathValidator.getRevocationChecker();
if ((additionalTrustRoots == null) || (additionalTrustRoots[0] == null)) {
trustedRootCerts = null;
} else {
trustedRootCerts = additionalTrustRoots.clone();
}
}
/**
* Constructor
*
* @param additionalTrustRoots trusted root certificates
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
*/
public ValidatePathWithParams(String[] additionalTrustRoots)
throws IOException, CertificateException, NoSuchAlgorithmException {
cf = CertificateFactory.getInstance("X509");
certPathValidator = CertPathValidator.getInstance("PKIX");
certPathChecker
= (PKIXRevocationChecker) certPathValidator.getRevocationChecker();
if ((additionalTrustRoots == null) || (additionalTrustRoots[0] == null)) {
trustedRootCerts = null;
} else {
trustedRootCerts = additionalTrustRoots.clone();
}
}
private void validateCertificateChain(List<X509Certificate> certList)
throws NoSuchAlgorithmException,
KeyStoreException,
InvalidAlgorithmParameterException,
CertificateException,
CertPathValidatorException
{
// By default on Oracle JRE, algorithm is PKIX
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// 'null' will initialise the tmf with the default CA certs installed
// with the JRE.
tmf.init((KeyStore) null);
X509TrustManager tm = (X509TrustManager) tmf.getTrustManagers()[0];
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
Set<TrustAnchor> anch = new HashSet<>();
for (X509Certificate cert : tm.getAcceptedIssuers())
{
anch.add(new TrustAnchor(cert, null));
}
PKIXParameters params = new PKIXParameters(anch);
Security.setProperty("ocsp.enable", "true");
params.setRevocationEnabled(true);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
try
{
cpv.validate(factory.generateCertPath(certList), params);
}
catch (CertPathValidatorException e)
{
System.out.println(e.getIndex());
//if the timestamp check fails because the cert is expired
//we allow this to continue (code 0)
if(e.getIndex() != 0)
{
throw e;
}
}
}
/**
* Constructor
*
* @param additionalTrustRoots trusted root certificates
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
*/
public ValidatePathWithParams(String[] additionalTrustRoots)
throws IOException, CertificateException, NoSuchAlgorithmException {
cf = CertificateFactory.getInstance("X509");
certPathValidator = CertPathValidator.getInstance("PKIX");
certPathChecker
= (PKIXRevocationChecker) certPathValidator.getRevocationChecker();
if ((additionalTrustRoots == null) || (additionalTrustRoots[0] == null)) {
trustedRootCerts = null;
} else {
trustedRootCerts = additionalTrustRoots.clone();
}
}
boolean validateCertificate(Certificate cert) {
boolean isValidated;
if (cert == null) {
return false;
}
try {
KeyStore keyStore = getTrustStore();
PKIXParameters parms = new PKIXParameters(keyStore);
parms.setRevocationEnabled(false);
CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); // PKIX
ArrayList<Certificate> start = new ArrayList<>();
start.add(cert);
CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT);
CertPath certPath = certFactory.generateCertPath(start);
certValidator.validate(certPath, parms);
isValidated = true;
} catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException
| CertificateException | CertPathValidatorException | CryptoException e) {
logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate"
+ cert.toString());
isValidated = false;
}
return isValidated;
}
/**
* Constructor
*
* @param additionalTrustRoots trusted root certificates
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
*/
public ValidatePathWithParams(String[] additionalTrustRoots)
throws IOException, CertificateException, NoSuchAlgorithmException {
cf = CertificateFactory.getInstance("X509");
certPathValidator = CertPathValidator.getInstance("PKIX");
certPathChecker
= (PKIXRevocationChecker) certPathValidator.getRevocationChecker();
if ((additionalTrustRoots == null) || (additionalTrustRoots[0] == null)) {
trustedRootCerts = null;
} else {
trustedRootCerts = additionalTrustRoots.clone();
}
}
/**
*
*/
private CertPathValidator getCertPathValidator()
throws GeneralSecurityException
{
if (certValidator == null) {
if (certProvider.length() > 0) {
certValidator = CertPathValidator.getInstance("PKIX", certProvider);
} else {
certValidator = CertPathValidator.getInstance("PKIX");
}
}
return certValidator;
}
/**
* Validate certificate path. As it is exception, no checks against revocation or time validity are done but path
* still have to be validated in order to find connection between certificate presented by server and root CA in
* KeyStore
*
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws InvalidAlgorithmParameterException
* @throws CertPathValidatorException
* @throws CertPathBuilderException
* @throws CertificateException
*/
private void validatePath(X509Certificate[] chain)
throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException,
CertPathValidatorException, CertPathBuilderException, CertificateException {
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
X509CertSelector certSelector = new X509CertSelector();
certSelector.setCertificate(chain[chain.length - 1]);
// checks against time validity aren't done here as it exceptions list
certSelector.setCertificateValid(null);
PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);
// no checks against revocation as it is exception
parameters.setRevocationEnabled(false);
CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
CertPath certPath = pathResult.getCertPath();
PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator
.validate(certPath, parameters);
X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();
if (trustedCert == null) {
throw new CertificateException("Certificate path failed");
} else {
Log.debug("ClientTrustManager: Trusted CA: " + trustedCert.getSubjectDN());
}
}
private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException {
try {
// Generate cert path
java.util.List certList = java.util.Arrays.asList(certs);
CertPath path = this.getCertificateFactory().generateCertPath(certList);
// Use the certificates in the keystore as TrustAnchors
PKIXParameters param = new PKIXParameters(ks);
// Do not check a revocation list
param.setRevocationEnabled(false);
// Verify the trust path using the above settings
String provider = properties
.getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
CertPathValidator certPathValidator;
if (provider == null || provider.length() == 0) {
certPathValidator = CertPathValidator.getInstance("PKIX");
} else {
certPathValidator = CertPathValidator.getInstance("PKIX", provider);
}
certPathValidator.validate(path, param);
} catch (NoSuchProviderException | NoSuchAlgorithmException | CertificateException |
InvalidAlgorithmParameterException | CertPathValidatorException | KeyStoreException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE, "certpath",
new Object[]{ex.getMessage()}, ex);
}
return true;
}
/**
* Attempts to build a certification chain for given certificate to verify
* it. Relies on a set of root CA certificates (trust anchors) and a set of
* intermediate certificates (to be used as part of the chain).
*/
private PKIXCertPathBuilderResult verifyCertificate(X509Certificate certificate, Set<X509Certificate> trustedRootCerts, Set<X509Certificate> intermediateCerts)
throws GeneralSecurityException {
// Create the selector that specifies the starting certificate
X509CertSelector selector = new X509CertSelector();
selector.setBasicConstraints(-2);
selector.setCertificate(certificate);
// Create the trust anchors (set of root CA certificates)
Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
for (X509Certificate trustedRootCert : trustedRootCerts) {
trustAnchors.add(new TrustAnchor(trustedRootCert, null));
}
// Configure the PKIX certificate builder algorithm parameters
PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
// Turn off default revocation-checking mechanism
pkixParams.setRevocationEnabled(false);
// Specify a list of intermediate certificates
CertStore intermediateCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts));
pkixParams.addCertStore(intermediateCertStore);
// Build and verify the certification chain
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
PKIXCertPathBuilderResult certPathBuilderResult = (PKIXCertPathBuilderResult) builder.build(pkixParams);
// Additional check to Verify cert path
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
PKIXCertPathValidatorResult certPathValidationResult = (PKIXCertPathValidatorResult) certPathValidator.validate(certPathBuilderResult.getCertPath(), pkixParams);
return certPathBuilderResult;
}
@Test
void generateCertPathValidator_test() {
CertPathValidator certPathValidator = CertificateUtil.createCertPathValidator();
assertThat(certPathValidator).isNotNull();
}
public static void main(String[] args) throws Exception {
String extension = args[0];
String targetHost = args[1];
// enable CRLDP and AIA extensions
System.setProperty("com.sun.security.enableCRLDP", "true");
System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
Path hostsFilePath = Paths.get(System.getProperty("test.src", ".")
+ File.separator + extension);
System.setProperty("jdk.net.hosts.file",
hostsFilePath.toFile().getAbsolutePath());
X509Certificate trustedCert = loadCertificate(CA_CERT);
X509Certificate eeCert = loadCertificate(EE_CERT);
Set<TrustAnchor> trustedCertsSet = new HashSet<>();
trustedCertsSet.add(new TrustAnchor(trustedCert, null));
CertPath cp = (CertPath) CertificateFactory.getInstance("X509")
.generateCertPath(Arrays.asList(eeCert));
// CertPath validator should try to parse CRLDP and AIA extensions,
// and load CRLs/certs which they point to.
// If proxy server catches requests for resolving host names
// which extensions contain, then it means that CertPath validator
// tried to load CRLs/certs which they point to.
List<String> hosts = new ArrayList<>();
Consumer<Socket> socketConsumer = (Socket socket) -> {
InetSocketAddress remoteAddress
= (InetSocketAddress) socket.getRemoteSocketAddress();
hosts.add(remoteAddress.getHostName());
};
try (SocksProxy proxy = SocksProxy.startProxy(socketConsumer)) {
CertPathValidator.getInstance("PKIX").validate(cp,
new PKIXParameters(trustedCertsSet));
throw new RuntimeException("CertPathValidatorException not thrown");
} catch (CertPathValidatorException cpve) {
System.out.println("Expected exception: " + cpve);
}
if (!hosts.contains(targetHost)) {
throw new RuntimeException(
String.format("The %s from %s extension is not requested",
targetHost, extension));
}
System.out.println("Test passed");
}
/**
* Test a case where client-side stapling is attempted, but does not
* occur because OCSP responders are unreachable. Client-side OCSP
* checking is enabled for this, with SOFT_FAIL.
*/
static void testSoftFailFallback() throws Exception {
ClientParameters cliParams = new ClientParameters();
ServerParameters servParams = new ServerParameters();
serverReady = false;
// make OCSP responders reject connections
intOcsp.rejectConnections();
rootOcsp.rejectConnections();
System.out.println("=======================================");
System.out.println("Stapling enbled in client and server,");
System.out.println("but OCSP responders disabled.");
System.out.println("PKIXParameters with Revocation checking");
System.out.println("enabled and SOFT_FAIL.");
System.out.println("=======================================");
Security.setProperty("ocsp.enable", "true");
cliParams.pkixParams = new PKIXBuilderParameters(trustStore,
new X509CertSelector());
cliParams.pkixParams.setRevocationEnabled(true);
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
cliParams.revChecker =
(PKIXRevocationChecker)cpv.getRevocationChecker();
cliParams.revChecker.setOptions(EnumSet.of(Option.SOFT_FAIL));
SSLSocketWithStapling sslTest = new SSLSocketWithStapling(cliParams,
servParams);
TestResult tr = sslTest.getResult();
if (tr.clientExc != null) {
throw tr.clientExc;
} else if (tr.serverExc != null) {
throw tr.serverExc;
}
System.out.println(" PASS");
System.out.println("=======================================\n");
// Make OCSP responders accept connections
intOcsp.acceptConnections();
rootOcsp.acceptConnections();
// Wait 5 seconds for server ready
for (int i = 0; (i < 100 && (!intOcsp.isServerReady() || !rootOcsp.isServerReady())); i++) {
Thread.sleep(50);
}
if (!intOcsp.isServerReady() || !rootOcsp.isServerReady()) {
throw new RuntimeException("Server not ready yet");
}
}
/**
* Validate certificate path
*
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws InvalidAlgorithmParameterException
* @throws CertPathValidatorException
* @throws CertPathBuilderException
* @throws CertificateException
*/
private void validatePath(X509Certificate[] chain)
throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException,
CertPathValidatorException, CertPathBuilderException, CertificateException {
// PKIX algorithm is defined in rfc3280
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
X509CertSelector certSelector = new X509CertSelector();
// set last certificate (often root CA) from chain for CertSelector so trust store must contain it
certSelector.setCertificate(chain[chain.length - 1]);
// checks against time validity aren't done here as are already done in checkDateValidity (X509Certificate[]
// chain)
certSelector.setCertificateValid(null);
// create parameters using trustStore as source of Trust Anchors and using X509CertSelector
PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);
// will use PKIXRevocationChecker (or nothing if revocation mechanisms are
// disabled) instead of the default revocation checker
parameters.setRevocationEnabled(false);
// if revoked certificates aren't accepted, but no revocation checks then only
// certificates from blacklist will be rejected
if (acceptRevoked == false) {
// OCSP checking is done according to Java PKI Programmer's Guide, PKIXRevocationChecker was added in Java 8:
// https://docs.oracle.com/javase/8/docs/technotes/guides/security/certpath/CertPathProgGuide.html#PKIXRevocationChecker
PKIXRevocationChecker checker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();
EnumSet<PKIXRevocationChecker.Option> checkerOptions = EnumSet.noneOf(PKIXRevocationChecker.Option.class);
// if soft fail isn't enabled then OCSP or CRL must pass validation, in case
// when any of them cannot be validated verification will fail, if soft fail
// is enabled then in case of network issues revocation checking is omitted
if (allowSoftFail) {
checkerOptions.add(PKIXRevocationChecker.Option.SOFT_FAIL);
}
// check OCSP, CRL serve as backup
if (checkOCSP && checkCRL) {
checker.setOptions(checkerOptions);
parameters.addCertPathChecker(checker);
} else if (!checkOCSP && checkCRL) {
// check only CRL, if CRL fail then there is no fallback to OCSP
checkerOptions.add(PKIXRevocationChecker.Option.PREFER_CRLS);
checkerOptions.add(PKIXRevocationChecker.Option.NO_FALLBACK);
checker.setOptions(checkerOptions);
parameters.addCertPathChecker(checker);
}
}
try {
CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
CertPath certPath = pathResult.getCertPath();
PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator
.validate(certPath, parameters);
X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();
if (trustedCert == null) {
throw new CertificateException("certificate path failed: Trusted CA is NULL");
}
// check if all certificates in path have Basic Constraints, only certificate that isn't required to have
// this extension is last certificate: root CA
for (int i = 0; i < chain.length - 1; i++) {
checkBasicConstraints(chain[i]);
}
} catch (CertificateRevokedException e) {
Log.warning("Certificate was revoked", e);
for (X509Certificate cert : chain) {
for (X509CRL crl : crlCollection) {
if (crl.isRevoked(cert)) {
try {
addToBlackList(cert);
} catch (IOException | HeadlessException | InvalidNameException e1) {
Log.error("Couldn't move to the blacklist", e1);
}
break;
}
}
}
throw new CertificateException("Certificate was revoked");
}
}
public void validate(Certificate[] certChain) throws CertificateException {
try {
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
for (Certificate item : certChain) {
if (item == null) continue;
if (!(item instanceof X509Certificate)) {
throw new IllegalStateException("Invalid certificate type in chain");
}
certList.add((X509Certificate)item);
}
if (certList.isEmpty()) {
throw new IllegalStateException("Invalid certificate chain");
}
X509CertSelector certSelect = new X509CertSelector();
certSelect.setCertificate(certList.get(0));
// Configure certification path builder parameters
PKIXBuilderParameters pbParams = new PKIXBuilderParameters(trustStore, certSelect);
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));
// Set maximum certification path length
pbParams.setMaxPathLength(maxCertPathLength);
// Enable revocation checking
pbParams.setRevocationEnabled(true);
// Set static Certificate Revocation List
if (crls != null && !crls.isEmpty()) {
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls)));
}
// Enable On-Line Certificate Status Protocol (OCSP) support
if (enableOCSP) {
Security.setProperty("ocsp.enable","true");
}
// Enable Certificate Revocation List Distribution Points (CRLDP) support
if (enableCRLDP) {
System.setProperty("com.sun.security.enableCRLDP","true");
}
// Build certification path
CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
// Validate certification path
CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
} catch (GeneralSecurityException gse) {
logger.debug("", gse);
throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
}
}
public void validate(Certificate[] certChain) throws CertificateException
{
try
{
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
for (Certificate item : certChain)
{
if (item == null)
continue;
if (!(item instanceof X509Certificate))
{
throw new IllegalStateException("Invalid certificate type in chain");
}
certList.add((X509Certificate)item);
}
if (certList.isEmpty())
{
throw new IllegalStateException("Invalid certificate chain");
}
X509CertSelector certSelect = new X509CertSelector();
certSelect.setCertificate(certList.get(0));
// Configure certification path builder parameters
PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect);
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));
// Set maximum certification path length
pbParams.setMaxPathLength(_maxCertPathLength);
// Enable revocation checking
pbParams.setRevocationEnabled(true);
// Set static Certificate Revocation List
if (_crls != null && !_crls.isEmpty())
{
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls)));
}
// Enable On-Line Certificate Status Protocol (OCSP) support
if (_enableOCSP)
{
Security.setProperty("ocsp.enable","true");
}
// Enable Certificate Revocation List Distribution Points (CRLDP) support
if (_enableCRLDP)
{
System.setProperty("com.sun.security.enableCRLDP","true");
}
// Build certification path
CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
// Validate certification path
CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
}
catch (GeneralSecurityException gse)
{
LOG.debug(gse);
throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
}
}
public void validate(Certificate[] certChain) throws CertificateException
{
try
{
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
for (Certificate item : certChain)
{
if (item == null)
continue;
if (!(item instanceof X509Certificate))
{
throw new IllegalStateException("Invalid certificate type in chain");
}
certList.add((X509Certificate)item);
}
if (certList.isEmpty())
{
throw new IllegalStateException("Invalid certificate chain");
}
X509CertSelector certSelect = new X509CertSelector();
certSelect.setCertificate(certList.get(0));
// Configure certification path builder parameters
PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect);
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));
// Set maximum certification path length
pbParams.setMaxPathLength(_maxCertPathLength);
// Enable revocation checking
pbParams.setRevocationEnabled(true);
// Set static Certificate Revocation List
if (_crls != null && !_crls.isEmpty())
{
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls)));
}
// Enable On-Line Certificate Status Protocol (OCSP) support
if (_enableOCSP)
{
Security.setProperty("ocsp.enable","true");
}
// Enable Certificate Revocation List Distribution Points (CRLDP) support
if (_enableCRLDP)
{
System.setProperty("com.sun.security.enableCRLDP","true");
}
// Build certification path
CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
// Validate certification path
CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
}
catch (GeneralSecurityException gse)
{
LOG.debug(gse);
throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
}
}
public void validate(Certificate[] certChain) throws CertificateException
{
try
{
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
for (Certificate item : certChain)
{
if (item == null)
continue;
if (!(item instanceof X509Certificate))
{
throw new IllegalStateException("Invalid certificate type in chain");
}
certList.add((X509Certificate)item);
}
if (certList.isEmpty())
{
throw new IllegalStateException("Invalid certificate chain");
}
X509CertSelector certSelect = new X509CertSelector();
certSelect.setCertificate(certList.get(0));
// Configure certification path builder parameters
PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect);
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));
// Set maximum certification path length
pbParams.setMaxPathLength(_maxCertPathLength);
// Enable revocation checking
pbParams.setRevocationEnabled(true);
// Set static Certificate Revocation List
if (_crls != null && !_crls.isEmpty())
{
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls)));
}
// Enable On-Line Certificate Status Protocol (OCSP) support
if (_enableOCSP)
{
Security.setProperty("ocsp.enable","true");
}
// Enable Certificate Revocation List Distribution Points (CRLDP) support
if (_enableCRLDP)
{
System.setProperty("com.sun.security.enableCRLDP","true");
}
// Build certification path
CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
// Validate certification path
CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
}
catch (GeneralSecurityException gse)
{
LOG.debug(gse);
throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
}
}