下面列出了怎么用java.security.cert.CertStore的API类实例代码及写法,或者点击链接到github查看源代码。
static synchronized CertStore getInstance(URICertStoreParameters params)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if (debug != null) {
debug.println("CertStore URI:" + params.getURI());
}
CertStore ucs = certStoreCache.get(params);
if (ucs == null) {
ucs = new UCS(new URICertStore(params), null, "URI", params);
certStoreCache.put(params, ucs);
} else {
if (debug != null) {
debug.println("URICertStore.getInstance: cache hit");
}
}
return ucs;
}
public static Collection<? extends Certificate> getCertificates(final PKIXCertStoreSelector selector, CertStore certStore)
throws CertStoreException
{
return certStore.getCertificates(new CertSelector()
{
public boolean match(Certificate certificate)
{
return (selector == null) ? true : selector.match(certificate);
}
public Object clone()
{
return this;
}
});
}
/**
* Creates a CertStore from information included in the AccessDescription
* object of a certificate's Authority Information Access Extension.
*/
static CertStore getInstance(AccessDescription ad) {
if (!ad.getAccessMethod().equals((Object)
AccessDescription.Ad_CAISSUERS_Id)) {
return null;
}
GeneralNameInterface gn = ad.getAccessLocation().getName();
if (!(gn instanceof URIName)) {
return null;
}
URI uri = ((URIName) gn).getURI();
try {
return URICertStore.getInstance
(new URICertStore.URICertStoreParameters(uri));
} catch (Exception ex) {
if (debug != null) {
debug.println("exception creating CertStore: " + ex);
ex.printStackTrace();
}
return null;
}
}
/**
* Creates a CertStore from information included in the AccessDescription
* object of a certificate's Authority Information Access Extension.
*/
static CertStore getInstance(AccessDescription ad) {
if (!ad.getAccessMethod().equals((Object)
AccessDescription.Ad_CAISSUERS_Id)) {
return null;
}
GeneralNameInterface gn = ad.getAccessLocation().getName();
if (!(gn instanceof URIName)) {
return null;
}
URI uri = ((URIName) gn).getURI();
try {
return URICertStore.getInstance
(new URICertStore.URICertStoreParameters(uri));
} catch (Exception ex) {
if (debug != null) {
debug.println("exception creating CertStore: " + ex);
ex.printStackTrace();
}
return null;
}
}
public static Collection<? extends CRL> getCRLs(final PKIXCRLStoreSelector selector, CertStore certStore)
throws CertStoreException
{
return certStore.getCRLs(new CRLSelector()
{
public boolean match(CRL crl)
{
return selector.match(crl);
}
public Object clone()
{
return this;
}
});
}
static synchronized CertStore getInstance(URICertStoreParameters params)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if (debug != null) {
debug.println("CertStore URI:" + params.uri);
}
CertStore ucs = certStoreCache.get(params);
if (ucs == null) {
ucs = new UCS(new URICertStore(params), null, "URI", params);
certStoreCache.put(params, ucs);
} else {
if (debug != null) {
debug.println("URICertStore.getInstance: cache hit");
}
}
return ucs;
}
/**
* Initializes a new instance that uses the specified JCE providers for CertPathBuilder
* and Signature.
* @param trustAnchors the keystore with the trust-anchors ({@code TrustedCertificateEntry})
* @param revocationEnabled whether revocation is enabled
* @param maxPathLength the maximum length of the certification paths
* @param certPathBuilderProvider the CertPathBuilder provider
* @param signatureProvider the Signature provider
* @param intermCertsAndCrls a set of {@code CertStore}s that contain certificates to be
* used in the construction of the certification path. May contain CRLs to be used
* if revocation is enabled
* @see xades4j.utils.FileSystemDirectoryCertStore
* @throws NoSuchAlgorithmException if there is no provider for PKIX CertPathBuilder
*/
public PKIXCertificateValidationProvider(
KeyStore trustAnchors,
boolean revocationEnabled,
int maxPathLength,
String certPathBuilderProvider,
String signatureProvider,
CertStore... intermCertsAndCrls) throws NoSuchAlgorithmException, NoSuchProviderException
{
if (null == trustAnchors)
{
throw new NullPointerException("Trust anchors cannot be null");
}
this.trustAnchors = trustAnchors;
this.revocationEnabled = revocationEnabled;
this.maxPathLength = maxPathLength;
this.certPathBuilder = certPathBuilderProvider == null ? CertPathBuilder.getInstance("PKIX") : CertPathBuilder.getInstance("PKIX", certPathBuilderProvider);
this.signatureProvider = signatureProvider;
this.intermCertsAndCrls = intermCertsAndCrls;
}
/**
* Creates a CertStore from information included in the AccessDescription
* object of a certificate's Authority Information Access Extension.
*/
static CertStore getInstance(AccessDescription ad) {
if (!ad.getAccessMethod().equals((Object)
AccessDescription.Ad_CAISSUERS_Id)) {
return null;
}
GeneralNameInterface gn = ad.getAccessLocation().getName();
if (!(gn instanceof URIName)) {
return null;
}
URI uri = ((URIName) gn).getURI();
try {
return URICertStore.getInstance
(new URICertStore.URICertStoreParameters(uri));
} catch (Exception ex) {
if (debug != null) {
debug.println("exception creating CertStore: " + ex);
ex.printStackTrace();
}
return null;
}
}
public ClientTrustManager(KeyStore trustTrust) {
super();
this.trustStore = trustTrust;
//Note: A reference of the Collection is used in the CertStore, so we can add CRL's
// after creating the CertStore.
crls = new ArrayList<>();
CollectionCertStoreParameters params = new CollectionCertStoreParameters(crls);
try {
crlStore = CertStore.getInstance("Collection", params);
}
catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException ex) {
Log.warn("ClientTrustManager: ",ex);
}
loadCRL();
}
public Collection engineGetCertificates(CertSelector certSelector)
throws CertStoreException
{
boolean searchAllStores = params.getSearchAllStores();
Iterator iter = params.getCertStores().iterator();
List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST;
while (iter.hasNext())
{
CertStore store = (CertStore)iter.next();
Collection certs = store.getCertificates(certSelector);
if (searchAllStores)
{
allCerts.addAll(certs);
}
else if (!certs.isEmpty())
{
return certs;
}
}
return allCerts;
}
static synchronized CertStore getInstance(URICertStoreParameters params)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if (debug != null) {
debug.println("CertStore URI:" + params.uri);
}
CertStore ucs = certStoreCache.get(params);
if (ucs == null) {
ucs = new UCS(new URICertStore(params), null, "URI", params);
certStoreCache.put(params, ucs);
} else {
if (debug != null) {
debug.println("URICertStore.getInstance: cache hit");
}
}
return ucs;
}
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));
}
public Collection engineGetCertificates(CertSelector certSelector)
throws CertStoreException
{
boolean searchAllStores = params.getSearchAllStores();
Iterator iter = params.getCertStores().iterator();
List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST;
while (iter.hasNext())
{
CertStore store = (CertStore)iter.next();
Collection certs = store.getCertificates(certSelector);
if (searchAllStores)
{
allCerts.addAll(certs);
}
else if (!certs.isEmpty())
{
return certs;
}
}
return allCerts;
}
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));
}
public static Collection<? extends Certificate> getCertificates(final PKIXCertStoreSelector selector, CertStore certStore)
throws CertStoreException
{
return certStore.getCertificates(new CertSelector()
{
public boolean match(Certificate certificate)
{
return (selector == null) ? true : selector.match(certificate);
}
public Object clone()
{
return this;
}
});
}
static synchronized CertStore getInstance(URICertStoreParameters params)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if (debug != null) {
debug.println("CertStore URI:" + params.uri);
}
CertStore ucs = certStoreCache.get(params);
if (ucs == null) {
ucs = new UCS(new URICertStore(params), null, "URI", params);
certStoreCache.put(params, ucs);
} else {
if (debug != null) {
debug.println("URICertStore.getInstance: cache hit");
}
}
return ucs;
}
/**
* Retrieves all certs from the specified CertStores that satisfy the
* requirements specified in the parameters and the current
* PKIX state (name constraints, policy constraints, etc).
*
* @param currentState the current state.
* Must be an instance of <code>ReverseState</code>
* @param certStores list of CertStores
*/
@Override
Collection<X509Certificate> getMatchingCerts
(State currState, List<CertStore> certStores)
throws CertStoreException, CertificateException, IOException
{
ReverseState currentState = (ReverseState) currState;
if (debug != null)
debug.println("In ReverseBuilder.getMatchingCerts.");
/*
* The last certificate could be an EE or a CA certificate
* (we may be building a partial certification path or
* establishing trust in a CA).
*
* Try the EE certs before the CA certs. It will be more
* common to build a path to an end entity.
*/
Collection<X509Certificate> certs =
getMatchingEECerts(currentState, certStores);
certs.addAll(getMatchingCACerts(currentState, certStores));
return certs;
}
static synchronized CertStore getInstance(URICertStoreParameters params)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if (debug != null) {
debug.println("CertStore URI:" + params.getURI());
}
CertStore ucs = certStoreCache.get(params);
if (ucs == null) {
ucs = new UCS(new URICertStore(params), null, "URI", params);
certStoreCache.put(params, ucs);
} else {
if (debug != null) {
debug.println("URICertStore.getInstance: cache hit");
}
}
return ucs;
}
/**
* Retrieves all certs from the specified CertStores that satisfy the
* requirements specified in the parameters and the current
* PKIX state (name constraints, policy constraints, etc).
*
* @param currentState the current state.
* Must be an instance of <code>ReverseState</code>
* @param certStores list of CertStores
*/
@Override
Collection<X509Certificate> getMatchingCerts
(State currState, List<CertStore> certStores)
throws CertStoreException, CertificateException, IOException
{
ReverseState currentState = (ReverseState) currState;
if (debug != null)
debug.println("In ReverseBuilder.getMatchingCerts.");
/*
* The last certificate could be an EE or a CA certificate
* (we may be building a partial certification path or
* establishing trust in a CA).
*
* Try the EE certs before the CA certs. It will be more
* common to build a path to an end entity.
*/
Collection<X509Certificate> certs =
getMatchingEECerts(currentState, certStores);
certs.addAll(getMatchingCACerts(currentState, certStores));
return certs;
}
static synchronized CertStore getInstance(URICertStoreParameters params)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if (debug != null) {
debug.println("CertStore URI:" + params.uri);
}
CertStore ucs = certStoreCache.get(params);
if (ucs == null) {
ucs = new UCS(new URICertStore(params), null, "URI", params);
certStoreCache.put(params, ucs);
} else {
if (debug != null) {
debug.println("URICertStore.getInstance: cache hit");
}
}
return ucs;
}
/**
* 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;
}
/**
* 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;
}
/**
* Download Certificates from the given AIA and add them to the
* specified Collection.
*/
// cs.getCertificates(caSelector) returns a collection of X509Certificate's
// because of the selector, so the cast is safe
@SuppressWarnings("unchecked")
private boolean getCerts(AuthorityInfoAccessExtension aiaExt,
Collection<X509Certificate> certs)
{
if (Builder.USE_AIA == false) {
return false;
}
List<AccessDescription> adList = aiaExt.getAccessDescriptions();
if (adList == null || adList.isEmpty()) {
return false;
}
boolean add = false;
for (AccessDescription ad : adList) {
CertStore cs = URICertStore.getInstance(ad);
if (cs != null) {
try {
if (certs.addAll((Collection<X509Certificate>)
cs.getCertificates(caSelector))) {
add = true;
if (!searchAllCertStores) {
return true;
}
}
} catch (CertStoreException cse) {
if (debug != null) {
debug.println("exception getting certs from CertStore:");
cse.printStackTrace();
}
}
}
}
return add;
}
/**
* Retrieves all certs from the specified CertStores that satisfy the
* requirements specified in the parameters and the current
* PKIX state (name constraints, policy constraints, etc).
*
* @param currentState the current state.
* Must be an instance of <code>ForwardState</code>
* @param certStores list of CertStores
*/
@Override
Collection<X509Certificate> getMatchingCerts(State currentState,
List<CertStore> certStores)
throws CertStoreException, CertificateException, IOException
{
if (debug != null) {
debug.println("ForwardBuilder.getMatchingCerts()...");
}
ForwardState currState = (ForwardState) currentState;
/*
* We store certs in a Set because we don't want duplicates.
* As each cert is added, it is sorted based on the PKIXCertComparator
* algorithm.
*/
Set<X509Certificate> certs = new TreeSet<>(comparator);
/*
* Only look for EE certs if search has just started.
*/
if (currState.isInitial()) {
getMatchingEECerts(currState, certStores, certs);
}
getMatchingCACerts(currState, certStores, certs);
return certs;
}
public static void main(String[] args) throws Exception {
try {
Class.forName("javax.naming.ldap.LdapName");
System.out.println("LDAP is present, test skipped");
return;
} catch (ClassNotFoundException ignore) { }
try {
CertStore.getInstance("LDAP", new LDAPCertStoreParameters());
throw new RuntimeException("NoSuchAlgorithmException expected");
} catch (NoSuchAlgorithmException x) {
System.out.println("NoSuchAlgorithmException thrown as expected");
}
}
/**
* 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 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));
}
public static void main(String[] args) throws Exception {
try {
Class.forName("javax.naming.ldap.LdapName");
System.out.println("LDAP is present, test skipped");
return;
} catch (ClassNotFoundException ignore) { }
try {
CertStore.getInstance("LDAP", new LDAPCertStoreParameters());
throw new RuntimeException("NoSuchAlgorithmException expected");
} catch (NoSuchAlgorithmException x) {
System.out.println("NoSuchAlgorithmException thrown as expected");
}
}