下面列出了javax.net.ssl.CertPathTrustManagerParameters#java.security.cert.CollectionCertStoreParameters 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static CertStore getCertStore() throws Exception {
ArrayList certsAndCrls = new ArrayList();
try {
ConfigValidator config = ConfigFactory.getConfigValidator();
KeyStore tslStore = KeyStore.getInstance(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.type", "JKS"));
tslStore.load(ConnectorIOUtils.getResourceAsStream(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.location")), config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.pwd", "").toCharArray());
Enumeration aliases = tslStore.aliases();
while(aliases.hasMoreElements()) {
String alias = (String)aliases.nextElement();
X509Certificate cert = (X509Certificate)tslStore.getCertificate(alias);
LOG.debug("Adding " + cert.getSubjectX500Principal().getName("RFC1779"));
certsAndCrls.add(cert);
}
} catch (Exception var6) {
LOG.error("Error while loading keystore", var6);
}
return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certsAndCrls));
}
private static CertStore getCertStore() throws Exception {
ArrayList certsAndCrls = new ArrayList();
try {
ConfigValidator config = ConfigFactory.getConfigValidator();
KeyStore tslStore = KeyStore.getInstance(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.type", "JKS"));
tslStore.load(ConnectorIOUtils.getResourceAsStream(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.location")), config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.pwd", "").toCharArray());
Enumeration aliases = tslStore.aliases();
while(aliases.hasMoreElements()) {
String alias = (String)aliases.nextElement();
X509Certificate cert = (X509Certificate)tslStore.getCertificate(alias);
LOG.debug("Adding " + cert.getSubjectX500Principal().getName("RFC1779"));
certsAndCrls.add(cert);
}
} catch (Exception var6) {
LOG.error("Error while loading keystore", var6);
}
return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certsAndCrls));
}
private static CertStore getCertStore() throws Exception {
ArrayList certsAndCrls = new ArrayList();
try {
ConfigValidator config = ConfigFactory.getConfigValidator();
KeyStore tslStore = KeyStore.getInstance(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.type", "JKS"));
tslStore.load(ConnectorIOUtils.getResourceAsStream(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.location")), config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.pwd", "").toCharArray());
Enumeration aliases = tslStore.aliases();
while(aliases.hasMoreElements()) {
String alias = (String)aliases.nextElement();
X509Certificate cert = (X509Certificate)tslStore.getCertificate(alias);
LOG.debug("Adding " + cert.getSubjectX500Principal().getName("RFC1779"));
certsAndCrls.add(cert);
}
} catch (Exception var6) {
LOG.error("Error while loading keystore", var6);
}
return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certsAndCrls));
}
private static CertStore getCertStore() throws Exception {
ArrayList certsAndCrls = new ArrayList();
try {
ConfigValidator config = ConfigFactory.getConfigValidator();
KeyStore tslStore = KeyStore.getInstance(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.type", "JKS"));
tslStore.load(ConnectorIOUtils.getResourceAsStream(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.location")), config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.pwd", "").toCharArray());
Enumeration aliases = tslStore.aliases();
while(aliases.hasMoreElements()) {
String alias = (String)aliases.nextElement();
X509Certificate cert = (X509Certificate)tslStore.getCertificate(alias);
LOG.debug("Adding " + cert.getSubjectX500Principal().getName("RFC1779"));
certsAndCrls.add(cert);
}
} catch (Exception var6) {
LOG.error("Error while loading keystore", var6);
}
return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certsAndCrls));
}
/**
* Return the initialization parameters for the TrustManager.
* Currently, only the default <code>PKIX</code> is supported.
*
* @param algorithm The algorithm to get parameters for.
* @param crlFilename The path to the CRL file.
* @param maxCertificateChainLength Optional maximum cert chain length.
* @param trustStore The configured TrustStore.
*
* @return The parameters including the TrustStore and any CRLs.
*
* @throws InvalidAlgorithmParameterException
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws CRLException
* @throws NoSuchAlgorithmException
*/
protected static CertPathParameters getParameters(String algorithm,
String crlFilename,
Integer maxCertificateChainLength,
KeyStore trustStore)
throws KeyStoreException, InvalidAlgorithmParameterException, CRLException, CertificateException, IOException, NoSuchAlgorithmException
{
CertPathParameters params = null;
if("PKIX".equalsIgnoreCase(algorithm)) {
PKIXBuilderParameters xparams =
new PKIXBuilderParameters(trustStore, new X509CertSelector());
Collection<? extends CRL> crls = getCRLs(crlFilename);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
xparams.addCertStore(store);
xparams.setRevocationEnabled(true);
if(maxCertificateChainLength != null)
xparams.setMaxPathLength(maxCertificateChainLength.intValue());
params = xparams;
} else {
throw new CRLException("CRLs not supported for type: " + algorithm);
}
return params;
}
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 void validateTrustChain(X509Certificate certificate,
List<X509Certificate> chain,
Set<X509Certificate> trustedCertificates,
Set<X509Certificate> authorityCertificates) throws UaException {
boolean certificateTrusted = trustedCertificates.stream()
.anyMatch(c -> Arrays.equals(certificate.getSignature(), c.getSignature()));
if (certificateTrusted) return;
try {
Set<TrustAnchor> trustAnchors = new HashSet<>();
authorityCertificates.forEach(ca -> trustAnchors.add(new TrustAnchor(ca, null)));
X509CertSelector selector = new X509CertSelector();
selector.setCertificate(certificate);
PKIXBuilderParameters params = new PKIXBuilderParameters(trustAnchors, selector);
params.setRevocationEnabled(false);
CertStore intermediateCertStore =
CertStore.getInstance("Collection", new CollectionCertStoreParameters(chain));
params.addCertStore(intermediateCertStore);
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(params);
LOGGER.debug("Validated certificate chain: {}", result.getCertPath());
} catch (Throwable t) {
throw new UaException(StatusCodes.Bad_SecurityChecksFailed);
}
}
private TrustManagerFactory loadTrustManagerFactory() throws Exception {
if (trustManagerFactoryPlugin != null) {
return AccessController.doPrivileged((PrivilegedAction<TrustManagerFactory>) () -> ((TrustManagerFactoryPlugin) ClassloadingUtil.newInstanceFromClassLoader(SSLSupport.class, trustManagerFactoryPlugin)).getTrustManagerFactory());
} else if (trustAll) {
//This is useful for testing but not should be used outside of that purpose
return InsecureTrustManagerFactory.INSTANCE;
} else if (truststorePath == null && (truststoreProvider == null || !"PKCS11".equals(truststoreProvider.toUpperCase()))) {
return null;
} else {
TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore trustStore = SSLSupport.loadKeystore(truststoreProvider, truststorePath, truststorePassword);
boolean ocsp = Boolean.valueOf(Security.getProperty("ocsp.enable"));
boolean initialized = false;
if ((ocsp || crlPath != null) && TrustManagerFactory.getDefaultAlgorithm().equalsIgnoreCase("PKIX")) {
PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustStore, new X509CertSelector());
if (crlPath != null) {
pkixParams.setRevocationEnabled(true);
Collection<? extends CRL> crlList = loadCRL();
if (crlList != null) {
pkixParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlList)));
}
}
trustMgrFactory.init(new CertPathTrustManagerParameters(pkixParams));
initialized = true;
}
if (!initialized) {
trustMgrFactory.init(trustStore);
}
return trustMgrFactory;
}
}
public static void main(String[] args) throws Exception {
// reset the security property to make sure that the algorithms
// and keys used in this test are not disabled.
Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
TrustAnchor anchor = new TrustAnchor
(rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
X509CertSelector sel = new X509CertSelector();
sel.setBasicConstraints(-2);
PKIXBuilderParameters params = new PKIXBuilderParameters
(Collections.singleton(anchor), sel);
params.setRevocationEnabled(false);
X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
certs.add(caCert);
certs.add(eeCert);
CollectionCertStoreParameters ccsp =
new CollectionCertStoreParameters(certs);
CertStore cs = CertStore.getInstance("Collection", ccsp);
params.addCertStore(cs);
PKIXCertPathBuilderResult res = CertUtils.build(params);
CertPath cp = res.getCertPath();
// check that first certificate is an EE cert
List<? extends Certificate> certList = cp.getCertificates();
X509Certificate cert = (X509Certificate) certList.get(0);
if (cert.getBasicConstraints() != -1) {
throw new Exception("Target certificate is not an EE certificate");
}
}
/**
* Read a bunch of certs from files and create a CertStore from them.
*
* @param relPath relative path containing certs (must end in
* file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createStore(String relPath, String [] fileNames)
throws Exception {
Set<X509Certificate> certs = new HashSet<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
certs.add(getCertFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(certs));
}
/**
* Read a bunch of CRLs from files and create a CertStore from them.
*
* @param relPath relative path containing CRLs (must end in file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createCRLStore(String relPath, String [] fileNames)
throws Exception {
Set<X509CRL> crls = new HashSet<X509CRL>();
for (int i = 0; i < fileNames.length; i++) {
crls.add(getCRLFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(crls));
}
private void doBuild(X509Certificate userCert) throws Exception {
// get the set of trusted CA certificates (only one in this instance)
HashSet trustAnchors = new HashSet();
X509Certificate trustedCert = getTrustedCertificate();
trustAnchors.add(new TrustAnchor(trustedCert, null));
// put together a CertStore (repository of the certificates and CRLs)
ArrayList certs = new ArrayList();
certs.add(trustedCert);
certs.add(userCert);
CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
CertStore certStore = CertStore.getInstance("Collection", certStoreParams);
// specify the target certificate via a CertSelector
X509CertSelector certSelector = new X509CertSelector();
certSelector.setCertificate(userCert);
certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required
// build a valid cerificate path
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
certPathBuilderParams.addCertStore(certStore);
certPathBuilderParams.setRevocationEnabled(false);
CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);
// get and show cert path
CertPath certPath = result.getCertPath();
// System.out.println(certPath.toString());
}
public CertStoreCollectionSpi(CertStoreParameters params)
throws InvalidAlgorithmParameterException
{
super(params);
if (!(params instanceof CollectionCertStoreParameters))
{
throw new InvalidAlgorithmParameterException("org.ripple.bouncycastle.jce.provider.CertStoreCollectionSpi: parameter must be a CollectionCertStoreParameters object\n" + params.toString());
}
this.params = (CollectionCertStoreParameters)params;
}
/**
* Read a bunch of certs from files and create a CertStore from them.
*
* @param relPath relative path containing certs (must end in
* file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createStore(String relPath, String [] fileNames)
throws Exception {
Set<X509Certificate> certs = new HashSet<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
certs.add(getCertFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(certs));
}
/**
* Read a bunch of CRLs from files and create a CertStore from them.
*
* @param relPath relative path containing CRLs (must end in file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createCRLStore(String relPath, String [] fileNames)
throws Exception {
Set<X509CRL> crls = new HashSet<X509CRL>();
for (int i = 0; i < fileNames.length; i++) {
crls.add(getCRLFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(crls));
}
private void doBuild(X509Certificate userCert) throws Exception {
// get the set of trusted CA certificates (only one in this instance)
HashSet trustAnchors = new HashSet();
X509Certificate trustedCert = getTrustedCertificate();
trustAnchors.add(new TrustAnchor(trustedCert, null));
// put together a CertStore (repository of the certificates and CRLs)
ArrayList certs = new ArrayList();
certs.add(trustedCert);
certs.add(userCert);
CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
CertStore certStore = CertStore.getInstance("Collection", certStoreParams);
// specify the target certificate via a CertSelector
X509CertSelector certSelector = new X509CertSelector();
certSelector.setCertificate(userCert);
certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required
// build a valid cerificate path
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
certPathBuilderParams.addCertStore(certStore);
certPathBuilderParams.setRevocationEnabled(false);
CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);
// get and show cert path
CertPath certPath = result.getCertPath();
// System.out.println(certPath.toString());
}
public static void main(String[] args) throws Exception {
// reset the security property to make sure that the algorithms
// and keys used in this test are not disabled.
Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
TrustAnchor anchor = new TrustAnchor
(rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
X509CertSelector sel = new X509CertSelector();
sel.setBasicConstraints(-2);
PKIXBuilderParameters params = new PKIXBuilderParameters
(Collections.singleton(anchor), sel);
params.setRevocationEnabled(false);
X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
certs.add(caCert);
certs.add(eeCert);
CollectionCertStoreParameters ccsp =
new CollectionCertStoreParameters(certs);
CertStore cs = CertStore.getInstance("Collection", ccsp);
params.addCertStore(cs);
PKIXCertPathBuilderResult res = CertUtils.build(params);
CertPath cp = res.getCertPath();
// check that first certificate is an EE cert
List<? extends Certificate> certList = cp.getCertificates();
X509Certificate cert = (X509Certificate) certList.get(0);
if (cert.getBasicConstraints() != -1) {
throw new Exception("Target certificate is not an EE certificate");
}
}
/**
* Read a bunch of certs from files and create a CertStore from them.
*
* @param relPath relative path containing certs (must end in
* file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createStore(String relPath, String [] fileNames)
throws Exception {
Set<X509Certificate> certs = new HashSet<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
certs.add(getCertFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(certs));
}
/**
* Test #2 for <code>CollectionCertStoreParameters(Collection)</code>
* constructor<br>
*/
public final void testCollectionCertStoreParametersCollection02() {
// just check that we able to create CollectionCertStoreParameters
// object passing Collection containing Object which is not
// a Certificate or CRL
Vector<String> certificates = new Vector<String>();
certificates.add(new String("Not a Certificate"));
new CollectionCertStoreParameters(certificates);
}
/**
* Based on https://svn.apache.org/repos/asf/cxf/tags/cxf-2.4.1/distribution/src/main/release/samples/sts_issue_operation/src/main/java/demo/sts/provider/cert/CertificateVerifier.java
*
* @param cert
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidAlgorithmParameterException
* @throws CertPathBuilderException
*/
public void verifyCertificate(X509Certificate cert) throws CertificateException, NoSuchAlgorithmException,
NoSuchProviderException, InvalidAlgorithmParameterException, CertPathBuilderException {
// Prepare a set of trusted root CA certificates
// and a set of intermediate certificates
// Create the selector that specifies the starting certificate
X509CertSelector selector = new X509CertSelector();
selector.setCertificate(cert);
// 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);
// Disable CRL checks (this is done manually as additional step)
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");
builder.build(pkixParams);
// Attempt to build the certification chain and verify it
// Check whether the certificate is revoked by the CRL
// given in its CRL distribution point extension
// CRLVerifier.verifyCertificateCRLs(cert);
// The chain is verified.
}
public static void main(String[] args) throws Exception {
// reset the security property to make sure that the algorithms
// and keys used in this test are not disabled.
Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
TrustAnchor anchor = new TrustAnchor
(rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
X509CertSelector sel = new X509CertSelector();
sel.setBasicConstraints(-2);
PKIXBuilderParameters params = new PKIXBuilderParameters
(Collections.singleton(anchor), sel);
params.setRevocationEnabled(false);
X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
certs.add(caCert);
certs.add(eeCert);
CollectionCertStoreParameters ccsp =
new CollectionCertStoreParameters(certs);
CertStore cs = CertStore.getInstance("Collection", ccsp);
params.addCertStore(cs);
PKIXCertPathBuilderResult res = CertUtils.build(params);
CertPath cp = res.getCertPath();
// check that first certificate is an EE cert
List<? extends Certificate> certList = cp.getCertificates();
X509Certificate cert = (X509Certificate) certList.get(0);
if (cert.getBasicConstraints() != -1) {
throw new Exception("Target certificate is not an EE certificate");
}
}
/**
* Read a bunch of certs from files and create a CertStore from them.
*
* @param relPath relative path containing certs (must end in
* file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createStore(String relPath, String [] fileNames)
throws Exception {
Set<X509Certificate> certs = new HashSet<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
certs.add(getCertFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(certs));
}
/**
* Read a bunch of CRLs from files and create a CertStore from them.
*
* @param relPath relative path containing CRLs (must end in file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createCRLStore(String relPath, String [] fileNames)
throws Exception {
Set<X509CRL> crls = new HashSet<X509CRL>();
for (int i = 0; i < fileNames.length; i++) {
crls.add(getCRLFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(crls));
}
/**
* Return the initialization parameters for the TrustManager.
* Currently, only the default <code>PKIX</code> is supported.
*
* @param algorithm The algorithm to get parameters for.
* @param crlf The path to the CRL file.
* @param trustStore The configured TrustStore.
* @return The parameters including the CRLs and TrustStore.
*/
protected CertPathParameters getParameters(String algorithm,
String crlf,
KeyStore trustStore)
throws Exception {
CertPathParameters params = null;
if("PKIX".equalsIgnoreCase(algorithm)) {
PKIXBuilderParameters xparams =
new PKIXBuilderParameters(trustStore, new X509CertSelector());
Collection<? extends CRL> crls = getCRLs(crlf);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
xparams.addCertStore(store);
xparams.setRevocationEnabled(true);
String trustLength = endpoint.getTrustMaxCertLength();
if(trustLength != null) {
try {
xparams.setMaxPathLength(Integer.parseInt(trustLength));
} catch(Exception ex) {
log.warn("Bad maxCertLength: "+trustLength);
}
}
params = xparams;
} else {
throw new CRLException("CRLs not supported for type: "+algorithm);
}
return params;
}
/**
* Creates the certificate store that will be used during validation.
*
* @param validationInfo PKIX validation information
* @param untrustedCredential credential to be validated
*
* @return certificate store used during validation
*
* @throws GeneralSecurityException thrown if the certificate store can not be created from the cert and CRL
* material
*/
protected CertStore buildCertStore(PKIXValidationInformation validationInfo, X509Credential untrustedCredential)
throws GeneralSecurityException {
log.trace("Creating cert store to use during path validation");
log.trace("Adding entity certificate chain to cert store");
List<Object> storeMaterial = new ArrayList<Object>(untrustedCredential.getEntityCertificateChain());
if (log.isTraceEnabled()) {
for (X509Certificate cert : untrustedCredential.getEntityCertificateChain()) {
log.trace(String.format("Added X509Certificate from entity cert chain to cert store "
+ "with subject name '%s' issued by '%s' with serial number '%s'",
x500DNHandler.getName(cert.getSubjectX500Principal()),
x500DNHandler.getName(cert.getIssuerX500Principal()),
cert.getSerialNumber().toString()));
}
}
Date now = new Date();
if (validationInfo.getCRLs() != null && !validationInfo.getCRLs().isEmpty()) {
log.trace("Processing CRL's from PKIX info set");
addCRLsToStoreMaterial(storeMaterial, validationInfo.getCRLs(), now);
}
if (untrustedCredential.getCRLs() != null && !untrustedCredential.getCRLs().isEmpty()
&& options.isProcessCredentialCRLs()) {
log.trace("Processing CRL's from untrusted credential");
addCRLsToStoreMaterial(storeMaterial, untrustedCredential.getCRLs(), now);
}
return CertStore.getInstance("Collection", new CollectionCertStoreParameters(storeMaterial));
}
private void doBuild(X509Certificate userCert) throws Exception {
// get the set of trusted CA certificates (only one in this instance)
HashSet trustAnchors = new HashSet();
X509Certificate trustedCert = getTrustedCertificate();
trustAnchors.add(new TrustAnchor(trustedCert, null));
// put together a CertStore (repository of the certificates and CRLs)
ArrayList certs = new ArrayList();
certs.add(trustedCert);
certs.add(userCert);
CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
CertStore certStore = CertStore.getInstance("Collection", certStoreParams);
// specify the target certificate via a CertSelector
X509CertSelector certSelector = new X509CertSelector();
certSelector.setCertificate(userCert);
certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required
// build a valid cerificate path
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
certPathBuilderParams.addCertStore(certStore);
certPathBuilderParams.setRevocationEnabled(false);
CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);
// get and show cert path
CertPath certPath = result.getCertPath();
// System.out.println(certPath.toString());
}
public static void main(String[] args) throws Exception {
// reset the security property to make sure that the algorithms
// and keys used in this test are not disabled.
Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
TrustAnchor anchor = new TrustAnchor
(rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
X509CertSelector sel = new X509CertSelector();
sel.setBasicConstraints(-2);
PKIXBuilderParameters params = new PKIXBuilderParameters
(Collections.singleton(anchor), sel);
params.setRevocationEnabled(false);
X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
certs.add(caCert);
certs.add(eeCert);
CollectionCertStoreParameters ccsp =
new CollectionCertStoreParameters(certs);
CertStore cs = CertStore.getInstance("Collection", ccsp);
params.addCertStore(cs);
PKIXCertPathBuilderResult res = CertUtils.build(params);
CertPath cp = res.getCertPath();
// check that first certificate is an EE cert
List<? extends Certificate> certList = cp.getCertificates();
X509Certificate cert = (X509Certificate) certList.get(0);
if (cert.getBasicConstraints() != -1) {
throw new Exception("Target certificate is not an EE certificate");
}
}
/**
* Read a bunch of certs from files and create a CertStore from them.
*
* @param relPath relative path containing certs (must end in
* file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createStore(String relPath, String [] fileNames)
throws Exception {
Set<X509Certificate> certs = new HashSet<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
certs.add(getCertFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(certs));
}
/**
* Read a bunch of CRLs from files and create a CertStore from them.
*
* @param relPath relative path containing CRLs (must end in file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createCRLStore(String relPath, String [] fileNames)
throws Exception {
Set<X509CRL> crls = new HashSet<X509CRL>();
for (int i = 0; i < fileNames.length; i++) {
crls.add(getCRLFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(crls));
}
/**
* Read a bunch of certs from files and create a CertStore from them.
*
* @param relPath relative path containing certs (must end in
* file.separator)
* @param fileNames an array of <code>String</code>s that are file names
* @return the <code>CertStore</code> created
* @throws Exception on error
*/
public static CertStore createStore(String relPath, String [] fileNames)
throws Exception {
Set<X509Certificate> certs = new HashSet<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
certs.add(getCertFromFile(relPath + fileNames[i]));
}
return CertStore.getInstance("Collection",
new CollectionCertStoreParameters(certs));
}