下面列出了怎么用java.security.cert.CRL的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Return the initialization parameters for the TrustManager.
* Currently, only the default <code>PKIX</code> is supported.
*
* @param crlf The path to the CRL file.
* @param trustStore The configured TrustStore.
* @param revocationEnabled Should the JSSE provider perform revocation
* checks? Ignored if {@code crlf} is non-null.
* Configuration of revocation checks are expected
* to be via proprietary JSSE provider methods.
* @return The parameters including the CRLs and TrustStore.
* @throws Exception An error occurred
*/
protected CertPathParameters getParameters(String crlf, KeyStore trustStore,
boolean revocationEnabled) throws Exception {
PKIXBuilderParameters xparams =
new PKIXBuilderParameters(trustStore, new X509CertSelector());
if (crlf != null && crlf.length() > 0) {
Collection<? extends CRL> crls = getCRLs(crlf);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
xparams.addCertStore(store);
xparams.setRevocationEnabled(true);
} else {
xparams.setRevocationEnabled(revocationEnabled);
}
xparams.setMaxPathLength(sslHostConfig.getCertificateVerificationDepth());
return xparams;
}
private void printCRL(CRL crl, PrintStream out)
throws Exception {
X509CRL xcrl = (X509CRL)crl;
if (rfc) {
out.println("-----BEGIN X509 CRL-----");
out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(xcrl.getEncoded()));
out.println("-----END X509 CRL-----");
} else {
String s;
if (crl instanceof X509CRLImpl) {
X509CRLImpl x509crl = (X509CRLImpl) crl;
s = x509crl.toStringWithAlgName(withWeak("" + x509crl.getSigAlgId()));
} else {
s = crl.toString();
}
out.println(s);
}
}
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
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;
}
});
}
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
return null;
}
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
return null;
}
private void printCRL(CRL crl, PrintStream out)
throws Exception {
X509CRL xcrl = (X509CRL)crl;
if (rfc) {
out.println("-----BEGIN X509 CRL-----");
out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(xcrl.getEncoded()));
out.println("-----END X509 CRL-----");
} else {
String s;
if (crl instanceof X509CRLImpl) {
X509CRLImpl x509crl = (X509CRLImpl) crl;
s = x509crl.toStringWithAlgName(withWeak("" + x509crl.getSigAlgId()));
} else {
s = crl.toString();
}
out.println(s);
}
}
private CRL readDERCRL(
InputStream in)
throws IOException, CRLException
{
ASN1InputStream dIn = new ASN1InputStream(in);
ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sData = new SignedData(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs();
return getCRL();
}
}
return new X509CRLObject(CertificateList.getInstance(seq));
}
/**
* 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 void checkCRL(X509Certificate[] chain) throws CertificateException {
String crl = option.getCrl();
crl = custom.getFullPath(crl);
File file = new File(crl);
if (!file.exists()) {
return;
}
CRL[] crls = KeyStoreUtil.createCRL(crl);
X509Certificate owner = CertificateUtil.findOwner(chain);
for (CRL c : crls) {
if (c.isRevoked(owner)) {
LOG.error("certificate revoked");
throw new CertificateException("certificate revoked");
}
}
}
private CRL readDERCRL(
InputStream in)
throws IOException, CRLException
{
ASN1InputStream dIn = new ASN1InputStream(in);
ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sData = new SignedData(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs();
return getCRL();
}
}
return new X509CRLObject(CertificateList.getInstance(seq));
}
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
return null;
}
private void printCRL(CRL crl, PrintStream out)
throws Exception {
X509CRL xcrl = (X509CRL)crl;
if (rfc) {
out.println("-----BEGIN X509 CRL-----");
out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(xcrl.getEncoded()));
out.println("-----END X509 CRL-----");
} else {
String s;
if (crl instanceof X509CRLImpl) {
X509CRLImpl x509crl = (X509CRLImpl) crl;
s = x509crl.toStringWithAlgName(withWeak("" + x509crl.getSigAlgId()));
} else {
s = crl.toString();
}
out.println(s);
}
}
private CRL readDERCRL(
ASN1InputStream aIn)
throws IOException, CRLException
{
ASN1Sequence seq = (ASN1Sequence)aIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sCrlData = SignedData.getInstance(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs();
return getCRL();
}
}
return createCRL(
CertificateList.getInstance(seq));
}
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
return null;
}
private void printCRL(CRL crl, PrintStream out)
throws Exception {
X509CRL xcrl = (X509CRL)crl;
if (rfc) {
out.println("-----BEGIN X509 CRL-----");
out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(xcrl.getEncoded()));
out.println("-----END X509 CRL-----");
} else {
String s;
if (crl instanceof X509CRLImpl) {
X509CRLImpl x509crl = (X509CRLImpl) crl;
s = x509crl.toStringWithAlgName(withWeak("" + x509crl.getSigAlgId()));
} else {
s = crl.toString();
}
out.println(s);
}
}
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
return null;
}
/**
* setMinCRLNumber(BigInteger minCRL) method testing. Tests if CRLs with any
* crl number value match the selector in the case of null crlNumber
* criteria, if specified minCRL value matches the selector, and if CRL with
* inappropriate crlNumber value does not match the selector.
*/
public void testSetMinCRLNumberLjava_math_BigInteger() {
X509CRLSelector selector = new X509CRLSelector();
BigInteger minCRL = new BigInteger("10000");
CRL crl = new TestCRL(minCRL);
selector.setMinCRLNumber(null);
assertTrue("Any CRL should match in the case of null minCRLNumber.",
selector.match(crl));
selector.setMinCRLNumber(minCRL);
assertTrue("The CRL should match the selection criteria.", selector
.match(crl));
selector.setMinCRLNumber(new BigInteger("10001"));
assertFalse("The CRL should not match the selection criteria.",
selector.match(crl));
}
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
return null;
}
/**
* Load the collection of CRLs.
*/
private Collection<? extends CRL> getCRLs(String crlUrl)
{
Collection<? extends CRL> crls = Collections.emptyList();
if (crlUrl != null)
{
try (InputStream is = getUrlFromString(crlUrl).openStream())
{
crls = SSLUtil.getCertificateFactory().generateCRLs(is);
}
catch (IOException | CRLException e)
{
throw new IllegalConfigurationException("Unable to load certificate revocation list '" + crlUrl +
"' for truststore '" + getName() + "' :" + e, e);
}
}
return crls;
}
/**
* Sets the crypto information to sign.
* @param privKey the private key
* @param certChain the certificate chain
* @param crlList the certificate revocation list. It can be <CODE>null</CODE>
*/
public void setSignInfo(PrivateKey privKey, Certificate[] certChain, CRL[] crlList) {
try {
pkcs = new PdfPKCS7(privKey, certChain, crlList, hashAlgorithm, provider, PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
pkcs.setExternalDigest(externalDigest, externalRSAdata, digestEncryptionAlgorithm);
if (PdfName.ADBE_X509_RSA_SHA1.equals(get(PdfName.SUBFILTER))) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
for (int k = 0; k < certChain.length; ++k) {
bout.write(certChain[k].getEncoded());
}
bout.close();
setCert(bout.toByteArray());
setContents(pkcs.getEncodedPKCS1());
}
else
setContents(pkcs.getEncodedPKCS7());
name = PdfPKCS7.getSubjectFields(pkcs.getSigningCertificate()).getField("CN");
if (name != null)
put(PdfName.NAME, new PdfString(name, PdfObject.TEXT_UNICODE));
pkcs = new PdfPKCS7(privKey, certChain, crlList, hashAlgorithm, provider, PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
pkcs.setExternalDigest(externalDigest, externalRSAdata, digestEncryptionAlgorithm);
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
return null;
}
/**
* Returns a (possibly empty) collection view of X.509 CRLs read
* from the given input stream <code>is</code>.
*
* @param is the input stream with the CRLs.
*
* @return a (possibly empty) collection view of X.509 CRL objects
* initialized with the data from the input stream.
*
* @exception CRLException on parsing errors.
*/
public Collection<? extends java.security.cert.CRL> engineGenerateCRLs(
InputStream is) throws CRLException
{
if (is == null) {
throw new CRLException("Missing input stream");
}
try {
return parseX509orPKCS7CRL(is);
} catch (IOException ioe) {
throw new CRLException(ioe.getMessage());
}
}
private void doPrintCRL(String src, PrintStream out)
throws Exception {
for (CRL crl: loadCRLs(src)) {
printCRL(crl, out);
String issuer = null;
if (caks != null) {
issuer = verifyCRL(caks, crl);
if (issuer != null) {
out.printf(rb.getString(
"verified.by.s.in.s"), issuer, "cacerts");
out.println();
}
}
if (issuer == null && keyStore != null) {
issuer = verifyCRL(keyStore, crl);
if (issuer != null) {
out.printf(rb.getString(
"verified.by.s.in.s"), issuer, "keystore");
out.println();
}
}
if (issuer == null) {
out.println(rb.getString
("STAR"));
out.println(rb.getString
("warning.not.verified.make.sure.keystore.is.correct"));
out.println(rb.getString
("STARNN"));
}
}
}
private void printCRL(CRL crl, PrintStream out)
throws Exception {
if (rfc) {
X509CRL xcrl = (X509CRL)crl;
out.println("-----BEGIN X509 CRL-----");
out.println(Base64.getMimeEncoder().encodeToString(xcrl.getEncoded()));
out.println("-----END X509 CRL-----");
} else {
out.println(crl.toString());
}
}
private CRL getCRL()
throws CRLException
{
if (sCrlData == null || sCrlDataObjectCount >= sCrlData.size())
{
return null;
}
return createCRL(
CertificateList.getInstance(
sCrlData.getObjectAt(sCrlDataObjectCount++)));
}
private CRL getCRL()
throws CRLException
{
if (sData == null || sDataObjectCount >= sData.size())
{
return null;
}
return new X509CRLObject(
CertificateList.getInstance(
sData.getObjectAt(sDataObjectCount++)));
}
public CertificateValidator(X509Certificate[] trustedCert, Collection<? extends CRL> crls)
{
if (trustedCert == null || trustedCert.length == 0)
{
throw new InvalidParameterException("trustedCert must be specified for CertificateValidator.");
}
_trustedCert = trustedCert;
_crls = crls;
}
@Test
public void testStaticCRL() throws Exception {
File staticCrl = getAbsoluteFilePathFromClassPath("crl/revoked.crl");
Collection<? extends CRL> crls = null;
try(FileInputStream crlin = new FileInputStream(staticCrl)) {
crls = CertificateFactory.getInstance("X.509").generateCRLs(crlin);
}
Assert.assertEquals(crls.size(), 1);
//trust chain incl intermediate certificates (root + intermediates)
Collection<? extends Certificate> rootCas;
final File trustedCas = getAbsoluteFilePathFromClassPath("chain-ca.pem");
try(FileInputStream trin = new FileInputStream(trustedCas)) {
rootCas = (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
}
Assert.assertEquals(rootCas.size(), 2);
//certificate chain to validate (client cert + intermediates but without root)
Collection<? extends Certificate> certsToValidate;
final File certs = getAbsoluteFilePathFromClassPath("crl/revoked.crt.pem");
try(FileInputStream trin = new FileInputStream(certs)) {
certsToValidate = (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
}
Assert.assertEquals(certsToValidate.size(), 2);
CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), crls);
validator.setDate(CRL_DATE);
try {
validator.validate(certsToValidate.toArray(new X509Certificate[0]));
Assert.fail();
} catch (CertificateException e) {
Assert.assertTrue(ExceptionUtils.getRootCause(e) instanceof CertificateRevokedException);
}
}
@Test
public void testStaticCRLOk() throws Exception {
File staticCrl = getAbsoluteFilePathFromClassPath("crl/revoked.crl");
Collection<? extends CRL> crls = null;
try(FileInputStream crlin = new FileInputStream(staticCrl)) {
crls = CertificateFactory.getInstance("X.509").generateCRLs(crlin);
}
Assert.assertEquals(crls.size(), 1);
//trust chain incl intermediate certificates (root + intermediates)
Collection<? extends Certificate> rootCas;
final File trustedCas = getAbsoluteFilePathFromClassPath("chain-ca.pem");
try(FileInputStream trin = new FileInputStream(trustedCas)) {
rootCas = (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
}
Assert.assertEquals(rootCas.size(), 2);
//certificate chain to validate (client cert + intermediates but without root)
Collection<? extends Certificate> certsToValidate;
final File certs = getAbsoluteFilePathFromClassPath("node-0.crt.pem");
try(FileInputStream trin = new FileInputStream(certs)) {
certsToValidate = (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
}
Assert.assertEquals(certsToValidate.size(), 3);
CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), crls);
validator.setDate(CRL_DATE);
try {
validator.validate(certsToValidate.toArray(new X509Certificate[0]));
} catch (CertificateException e) {
Assert.fail(ExceptionsHelper.stackTrace(ExceptionUtils.getRootCause(e)));
}
}