下面列出了怎么用java.security.cert.X509CertSelector的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns an instance of <code>ExtendedPKIXParameters</code> which can be
* safely casted to <code>ExtendedPKIXBuilderParameters</code>.
* <p>
* This method can be used to get a copy from other
* <code>PKIXBuilderParameters</code>, <code>PKIXParameters</code>,
* and <code>ExtendedPKIXParameters</code> instances.
*
* @param pkixParams The PKIX parameters to create a copy of.
* @return An <code>ExtendedPKIXBuilderParameters</code> instance.
*/
public static ExtendedPKIXParameters getInstance(PKIXParameters pkixParams)
{
ExtendedPKIXBuilderParameters params;
try
{
params = new ExtendedPKIXBuilderParameters(pkixParams
.getTrustAnchors(), X509CertStoreSelector
.getInstance((X509CertSelector) pkixParams
.getTargetCertConstraints()));
}
catch (Exception e)
{
// cannot happen
throw new RuntimeException(e.getMessage());
}
params.setParams(pkixParams);
return params;
}
/**
* Returns an X509CertSelector for matching on the authority key
* identifier, or null if not applicable.
*/
private X509CertSelector getSelector(X509CertImpl previousCert)
throws IOException {
if (previousCert != null) {
AuthorityKeyIdentifierExtension akidExt =
previousCert.getAuthorityKeyIdentifierExtension();
if (akidExt != null) {
byte[] skid = akidExt.getEncodedKeyIdentifier();
if (skid != null) {
X509CertSelector selector = new X509CertSelector();
selector.setSubjectKeyIdentifier(skid);
return selector;
}
}
}
return null;
}
private void testPrivateKeyValid() throws IOException, CertificateException {
System.out.println("X.509 Certificate Match on privateKeyValid");
// bad match
X509CertSelector selector = new X509CertSelector();
Calendar cal = Calendar.getInstance();
cal.set(1968, 12, 31);
selector.setPrivateKeyValid(cal.getTime());
checkMatch(selector, cert, false);
// good match
DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.16"));
byte[] encoded = in.getOctetString();
PrivateKeyUsageExtension ext = new PrivateKeyUsageExtension(false, encoded);
Date validDate = (Date) ext.get(PrivateKeyUsageExtension.NOT_BEFORE);
selector.setPrivateKeyValid(validDate);
checkMatch(selector, cert, true);
}
/**
* Returns an X509CertSelector for matching on the authority key
* identifier, or null if not applicable.
*/
private X509CertSelector getSelector(X509CertImpl previousCert)
throws IOException {
if (previousCert != null) {
AuthorityKeyIdentifierExtension akidExt =
previousCert.getAuthorityKeyIdentifierExtension();
if (akidExt != null) {
byte[] skid = akidExt.getEncodedKeyIdentifier();
if (skid != null) {
X509CertSelector selector = new X509CertSelector();
selector.setSubjectKeyIdentifier(skid);
return selector;
}
}
}
return null;
}
private void testPrivateKeyValid() throws IOException, CertificateException {
System.out.println("X.509 Certificate Match on privateKeyValid");
// bad match
X509CertSelector selector = new X509CertSelector();
Calendar cal = Calendar.getInstance();
cal.set(1968, 12, 31);
selector.setPrivateKeyValid(cal.getTime());
checkMatch(selector, cert, false);
// good match
DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.16"));
byte[] encoded = in.getOctetString();
PrivateKeyUsageExtension ext = new PrivateKeyUsageExtension(false, encoded);
Date validDate = (Date) ext.get(PrivateKeyUsageExtension.NOT_BEFORE);
selector.setPrivateKeyValid(validDate);
checkMatch(selector, cert, true);
}
/**
* Returns an X509CertSelector for matching on the authority key
* identifier, or null if not applicable.
*/
private X509CertSelector getSelector(X509CertImpl previousCert)
throws IOException {
if (previousCert != null) {
AuthorityKeyIdentifierExtension akidExt =
previousCert.getAuthorityKeyIdentifierExtension();
if (akidExt != null) {
byte[] skid = akidExt.getEncodedKeyIdentifier();
if (skid != null) {
X509CertSelector selector = new X509CertSelector();
selector.setSubjectKeyIdentifier(skid);
return selector;
}
}
}
return null;
}
private static void dumpTsloStore() {
if (LOG.isDebugEnabled()) {
try {
LOG.debug("Content of TSLO store");
Collection<? extends Certificate> tsloCerts = tsloStore.getCertificates(new X509CertSelector());
Iterator i$ = tsloCerts.iterator();
while(i$.hasNext()) {
Certificate tsloCert = (Certificate)i$.next();
X509Certificate x509 = (X509Certificate)tsloCert;
LOG.debug(" - " + x509.getSubjectX500Principal().getName("RFC1779"));
}
} catch (Exception var4) {
LOG.debug("Unable to print content of TSLO Store", var4);
}
}
}
private static void dumpTsloStore() {
if (LOG.isDebugEnabled()) {
try {
LOG.debug("Content of TSLO store");
Collection<? extends Certificate> tsloCerts = tsloStore.getCertificates(new X509CertSelector());
Iterator i$ = tsloCerts.iterator();
while(i$.hasNext()) {
Certificate tsloCert = (Certificate)i$.next();
X509Certificate x509 = (X509Certificate)tsloCert;
LOG.debug(" - " + x509.getSubjectX500Principal().getName("RFC1779"));
}
} catch (Exception var4) {
LOG.debug("Unable to print content of TSLO Store", var4);
}
}
}
public static void createPath(String[] certs) throws Exception {
TrustAnchor anchor = new TrustAnchor(getCertFromFile(certs[0]), null);
List list = new ArrayList();
for (int i = 1; i < certs.length; i++) {
list.add(0, getCertFromFile(certs[i]));
}
CertificateFactory cf = CertificateFactory.getInstance("X509");
path = cf.generateCertPath(list);
Set anchors = Collections.singleton(anchor);
params = new PKIXParameters(anchors);
params.setRevocationEnabled(false);
X509CertSelector sel = new X509CertSelector();
sel.setSerialNumber(new BigInteger("1427"));
params.setTargetCertConstraints(sel);
}
private static void dumpTsloStore() {
if (LOG.isDebugEnabled()) {
try {
LOG.debug("Content of TSLO store");
Collection<? extends Certificate> tsloCerts = tsloStore.getCertificates(new X509CertSelector());
Iterator i$ = tsloCerts.iterator();
while(i$.hasNext()) {
Certificate tsloCert = (Certificate)i$.next();
X509Certificate x509 = (X509Certificate)tsloCert;
LOG.debug(" - " + x509.getSubjectX500Principal().getName("RFC1779"));
}
} catch (Exception var4) {
LOG.debug("Unable to print content of TSLO Store", var4);
}
}
}
/**
* Returns an X509CertSelector for matching on the authority key
* identifier, or null if not applicable.
*/
private X509CertSelector getSelector(X509CertImpl previousCert)
throws IOException {
if (previousCert != null) {
AuthorityKeyIdentifierExtension akidExt =
previousCert.getAuthorityKeyIdentifierExtension();
if (akidExt != null) {
byte[] skid = akidExt.getEncodedKeyIdentifier();
if (skid != null) {
X509CertSelector selector = new X509CertSelector();
selector.setSubjectKeyIdentifier(skid);
return selector;
}
}
}
return null;
}
private Set getCACertificates(X509CertSelector xselector)
throws CertStoreException
{
String[] attrs = {params.getCACertificateAttribute()};
String attrName = params.getLdapCACertificateAttributeName();
String subjectAttributeName = params
.getCACertificateSubjectAttributeName();
Set set = certSubjectSerialSearch(xselector, attrs, attrName,
subjectAttributeName);
if (set.isEmpty())
{
set.addAll(search(null, "*", attrs));
}
return set;
}
@Test
public void testValidateNist() throws Exception
{
System.out.println("validateNist");
FileSystemDirectoryCertStore certStore = new FileSystemDirectoryCertStore("./src/test/cert/csrc.nist");
KeyStore ks = KeyStore.getInstance("jks");
FileInputStream fis = new FileInputStream("./src/test/cert/csrc.nist/trustAnchor");
ks.load(fis, "password".toCharArray());
fis.close();
X509CertSelector certSelector = new X509CertSelector();
certSelector.setSubject(new X500Principal("CN = User1-CP.02.01,OU = Testing,OU = DoD,O = U.S. Government,C = US"));
Collection<X509Certificate> otherCerts = Collections.emptyList();
PKIXCertificateValidationProvider instance = new PKIXCertificateValidationProvider(ks, true, certStore.getStore());
ValidationData result = instance.validate(certSelector, new Date(), otherCerts);
assertEquals(result.getCerts().size(), 4);
assertEquals(result.getCrls().size(), 3);
}
@Override
public X509CertSelector wrap(X509CertSelector selector,
X500Principal certSubject,
String ldapDN)
throws IOException
{
throw new UnsupportedOperationException();
}
/**
* Returns an instance of this from a <code>X509CertSelector</code>.
*
* @param selector A <code>X509CertSelector</code> instance.
* @return An instance of an <code>X509CertStoreSelector</code>.
* @exception IllegalArgumentException if selector is null or creation fails.
*/
public static X509CertStoreSelector getInstance(X509CertSelector selector)
{
if (selector == null)
{
throw new IllegalArgumentException("cannot create from null selector");
}
X509CertStoreSelector cs = new X509CertStoreSelector();
cs.setAuthorityKeyIdentifier(selector.getAuthorityKeyIdentifier());
cs.setBasicConstraints(selector.getBasicConstraints());
cs.setCertificate(selector.getCertificate());
cs.setCertificateValid(selector.getCertificateValid());
cs.setMatchAllSubjectAltNames(selector.getMatchAllSubjectAltNames());
try
{
cs.setPathToNames(selector.getPathToNames());
cs.setExtendedKeyUsage(selector.getExtendedKeyUsage());
cs.setNameConstraints(selector.getNameConstraints());
cs.setPolicy(selector.getPolicy());
cs.setSubjectPublicKeyAlgID(selector.getSubjectPublicKeyAlgID());
cs.setSubjectAlternativeNames(selector.getSubjectAlternativeNames());
}
catch (IOException e)
{
throw new IllegalArgumentException("error in passed in selector: " + e);
}
cs.setIssuer(selector.getIssuer());
cs.setKeyUsage(selector.getKeyUsage());
cs.setPrivateKeyValid(selector.getPrivateKeyValid());
cs.setSerialNumber(selector.getSerialNumber());
cs.setSubject(selector.getSubject());
cs.setSubjectKeyIdentifier(selector.getSubjectKeyIdentifier());
cs.setSubjectPublicKey(selector.getSubjectPublicKey());
return cs;
}
@Override
public X509CertSelector wrap(X509CertSelector selector,
X500Principal certSubject,
String ldapDN)
throws IOException
{
throw new UnsupportedOperationException();
}
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");
}
}
/**
* 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 void testSubject() throws IOException {
System.out.println("X.509 Certificate Match on subject");
// bad match
X509CertSelector selector = new X509CertSelector();
selector.setSubject("ou=bogus,ou=east,o=sun,c=us");
checkMatch(selector, cert, false);
// good match
selector.setSubject(cert.getSubjectX500Principal().getName("RFC2253"));
checkMatch(selector, cert, true);
}
private void testIssuer() throws IOException {
System.out.println("X.509 Certificate Match on issuer");
// bad match
X509CertSelector selector = new X509CertSelector();
selector.setIssuer("ou=bogus,ou=east,o=sun,c=us");
checkMatch(selector, cert, false);
// good match
selector.setIssuer((cert.getIssuerX500Principal()).getName("RFC2253"));
checkMatch(selector, cert, true);
}
private void testSerialNumber() {
System.out.println("X.509 Certificate Match on serialNumber");
// bad match
X509CertSelector selector = new X509CertSelector();
selector.setSerialNumber(new BigInteger("999999999"));
checkMatch(selector, cert, false);
// good match
selector.setSerialNumber(cert.getSerialNumber());
checkMatch(selector, cert, true);
}
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());
}
private void testBasicConstraints() {
System.out.println("X.509 Certificate Match on basic constraints");
// bad match
X509CertSelector selector = new X509CertSelector();
int mpl = cert.getBasicConstraints();
selector.setBasicConstraints(0);
checkMatch(selector, cert, false);
// good match
selector.setBasicConstraints(mpl);
checkMatch(selector, cert, true);
}
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());
}
private void testSubjectPublicKey() throws IOException, GeneralSecurityException {
System.out.println("X.509 Certificate Match on subject public key");
// bad match
X509CertSelector selector = new X509CertSelector();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
Base64.getMimeDecoder().decode(testKey.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
selector.setSubjectPublicKey(pubKey);
checkMatch(selector, cert, false);
// good match
selector.setSubjectPublicKey(cert.getPublicKey());
checkMatch(selector, cert, true);
}
private void testKeyUsage() {
System.out.println("X.509 Certificate Match on keyUsage");
// bad match
X509CertSelector selector = new X509CertSelector();
boolean[] keyUsage = { true, false, true, false, true, false, true, false };
selector.setKeyUsage(keyUsage);
System.out.println("Selector = " + selector.toString());
checkMatch(selector, cert, false);
// good match
selector.setKeyUsage(cert.getKeyUsage());
System.out.println("Selector = " + selector.toString());
checkMatch(selector, cert, true);
}
private void testBasicConstraints() {
System.out.println("X.509 Certificate Match on basic constraints");
// bad match
X509CertSelector selector = new X509CertSelector();
int mpl = cert.getBasicConstraints();
selector.setBasicConstraints(0);
checkMatch(selector, cert, false);
// good match
selector.setBasicConstraints(mpl);
checkMatch(selector, cert, true);
}
private void testSubject() throws IOException {
System.out.println("X.509 Certificate Match on subject");
// bad match
X509CertSelector selector = new X509CertSelector();
selector.setSubject("ou=bogus,ou=east,o=sun,c=us");
checkMatch(selector, cert, false);
// good match
selector.setSubject(cert.getSubjectX500Principal().getName("RFC2253"));
checkMatch(selector, cert, true);
}
private void testIssuer() throws IOException {
System.out.println("X.509 Certificate Match on issuer");
// bad match
X509CertSelector selector = new X509CertSelector();
selector.setIssuer("ou=bogus,ou=east,o=sun,c=us");
checkMatch(selector, cert, false);
// good match
selector.setIssuer((cert.getIssuerX500Principal()).getName("RFC2253"));
checkMatch(selector, cert, true);
}
private void testSubjectAltName() throws IOException {
System.out.println("X.509 Certificate Match on subjectAltName");
// bad match
X509CertSelector selector = new X509CertSelector();
GeneralNameInterface dnsName = new DNSName("foo.com");
DerOutputStream tmp = new DerOutputStream();
dnsName.encode(tmp);
selector.addSubjectAlternativeName(2, tmp.toByteArray());
checkMatch(selector, cert, false);
// good match
DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.17"));
byte[] encoded = in.getOctetString();
SubjectAlternativeNameExtension ext = new SubjectAlternativeNameExtension(false, encoded);
GeneralNames names = (GeneralNames) ext.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
GeneralName name = (GeneralName) names.get(0);
selector.setSubjectAlternativeNames(null);
DerOutputStream tmp2 = new DerOutputStream();
name.getName().encode(tmp2);
selector.addSubjectAlternativeName(name.getType(), tmp2.toByteArray());
checkMatch(selector, cert, true);
// good match 2 (matches at least one)
selector.setMatchAllSubjectAltNames(false);
selector.addSubjectAlternativeName(2, "foo.com");
checkMatch(selector, cert, true);
}