下面列出了怎么用java.security.cert.X509CRL的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testWriteCRLX509() throws IOException,
OperatorCreationException, CertificateException, CRLException {
X500Name issuer = x509CertificateHolder.getIssuer();
Date now = new Date();
X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now);
builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now,
CRLReason.cACompromise);
byte[] crlBytes = TMP_CRL_ENTRY.getBytes();
try (InputStream inStream = new ByteArrayInputStream(crlBytes)) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509CRL crl = (X509CRL)cf.generateCRL(inStream);
CRLCodec crlCodec = new CRLCodec(securityConfig);
crlCodec.writeCRL(crl);
// verify file generated or not
File crlFile =
Paths.get(crlCodec.getLocation().toString(),
this.securityConfig.getCrlName()).toFile();
assertTrue(crlFile.exists());
}
}
@Test
public void testGetX509CRLFromCRLHolder() throws IOException,
OperatorCreationException, CertificateException, CRLException {
X500Name issuer = x509CertificateHolder.getIssuer();
Date now = new Date();
X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now);
builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now,
CRLReason.cACompromise);
JcaContentSignerBuilder contentSignerBuilder =
new JcaContentSignerBuilder(securityConfig.getSignatureAlgo());
contentSignerBuilder.setProvider(securityConfig.getProvider());
PrivateKey privateKey = keyPair.getPrivate();
X509CRLHolder cRLHolder =
builder.build(contentSignerBuilder.build(privateKey));
CRLCodec crlCodec = new CRLCodec(securityConfig);
X509CRL crl = crlCodec.getX509CRL(cRLHolder);
assertNotNull(crl);
}
/**
* Get a list of the Java {@link java.security.cert.X509CRL}s within the given {@link X509Data}.
*
* @param x509Data {@link X509Data} to extract the CRLs from
*
* @return a list of Java {@link java.security.cert.X509CRL}s
*
* @throws CRLException thrown if there is a problem converting the
* CRL data into {@link java.security.cert.X509CRL}s
*/
public static List<X509CRL> getCRLs(X509Data x509Data) throws CRLException {
List<X509CRL> crlList = new LinkedList<X509CRL>();
if (x509Data == null) {
return crlList;
}
for (org.opensaml.xml.signature.X509CRL xmlCRL : x509Data.getX509CRLs()) {
if (xmlCRL != null && xmlCRL.getValue() != null) {
X509CRL newCRL = getCRL(xmlCRL);
crlList.add(newCRL);
}
}
return crlList;
}
/**
* Extract the issuer X500Principal from an X509CRL. Parses the encoded
* form of the CRL to preserve the principal's ASN.1 encoding.
*
* Called by java.security.cert.X509CRL.getIssuerX500Principal().
*/
public static X500Principal getIssuerX500Principal(X509CRL crl) {
try {
byte[] encoded = crl.getEncoded();
DerInputStream derIn = new DerInputStream(encoded);
DerValue tbsCert = derIn.getSequence(3)[0];
DerInputStream tbsIn = tbsCert.data;
DerValue tmp;
// skip version number if present
byte nextByte = (byte)tbsIn.peekByte();
if (nextByte == DerValue.tag_Integer) {
tmp = tbsIn.getDerValue();
}
tmp = tbsIn.getDerValue(); // skip signature
tmp = tbsIn.getDerValue(); // issuer
byte[] principalBytes = tmp.toByteArray();
return new X500Principal(principalBytes);
} catch (Exception e) {
throw new RuntimeException("Could not parse issuer", e);
}
}
public Path createCrl(final KeyCertificatePair caPair, final X509Certificate... certificate) throws CRLException
{
final X509CRL crl = TlsResourceBuilder.createCertificateRevocationList(caPair, certificate);
try
{
final Path pkFile = createFile(".crl");
try (FileOutputStream out = new FileOutputStream(pkFile.toFile()))
{
TlsResourceHelper.saveCrlAsPem(out, crl);
}
return pkFile;
}
catch (IOException e)
{
throw new CRLException(e);
}
}
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);
}
}
public void addOptionalAfterSignatureParts(UnsignedPropertiesBuilder unsignedProps, XMLSignature sig, String uuid, Map<String, Object> options) throws TechnicalConnectorException {
try {
X509Certificate signing = sig.getKeyInfo().getX509Certificate();
OCSPData ocsp = (OCSPData)OCSPCheckerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.RECEIVER_MANDATORY).build().validate(signing).getData();
unsignedProps.addCertificate(signing);
Iterator i$ = ocsp.getCrls().iterator();
while(i$.hasNext()) {
X509CRL crl = (X509CRL)i$.next();
unsignedProps.addCrlRef(crl);
}
unsignedProps.addOCSPRef(this.convertToOCSPResp(ocsp));
} catch (Exception var9) {
throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var9, new Object[]{"Unable to add optional Signature parts"});
}
}
public void saveCRL(X509CRL crl, UseKeyWithType id) {
String name = crl.getIssuerX500Principal().getName();
try {
String path = convertIdForFileSystem(name) + ".cer";
File certFile = new File(storageDir + "/" + CRLS_PATH, path);
certFile.getParentFile().mkdirs();
try (OutputStream os = Files.newOutputStream(certFile.toPath());
BufferedOutputStream bos = new BufferedOutputStream(os)) {
bos.write(crl.getEncoded());
bos.close();
}
} catch (Exception e) {
throw new RuntimeException("Error saving CRL " + name + ": " + e.getMessage(), e);
}
}
private Collection<X509CRL> loadCRLFromFile(CertificateFactory cf, String relativePath) throws GeneralSecurityException {
try {
String configDir = System.getProperty("jboss.server.config.dir");
if (configDir != null) {
File f = new File(configDir + File.separator + relativePath);
if (f.isFile()) {
logger.debugf("Loading CRL from %s", f.getAbsolutePath());
if (!f.canRead()) {
throw new IOException(String.format("Unable to read CRL from \"%s\"", f.getAbsolutePath()));
}
X509CRL crl = loadFromStream(cf, new FileInputStream(f.getAbsolutePath()));
return Collections.singleton(crl);
}
}
}
catch(IOException ex) {
logger.errorf(ex.getMessage());
}
return Collections.emptyList();
}
/**
* Extract the issuer X500Principal from an X509CRL. Parses the encoded
* form of the CRL to preserve the principal's ASN.1 encoding.
*
* Called by java.security.cert.X509CRL.getIssuerX500Principal().
*/
public static X500Principal getIssuerX500Principal(X509CRL crl) {
try {
byte[] encoded = crl.getEncoded();
DerInputStream derIn = new DerInputStream(encoded);
DerValue tbsCert = derIn.getSequence(3)[0];
DerInputStream tbsIn = tbsCert.data;
DerValue tmp;
// skip version number if present
byte nextByte = (byte)tbsIn.peekByte();
if (nextByte == DerValue.tag_Integer) {
tmp = tbsIn.getDerValue();
}
tmp = tbsIn.getDerValue(); // skip signature
tmp = tbsIn.getDerValue(); // issuer
byte[] principalBytes = tmp.toByteArray();
return new X500Principal(principalBytes);
} catch (Exception e) {
throw new RuntimeException("Could not parse issuer", e);
}
}
public CRLCertificateVerifier(final int maxCrlSize) {
SecurityProviderUtility.installBCProvider(true);
this.maxCrlSize = maxCrlSize;
CacheLoader<String, X509CRL> checkedLoader = new CacheLoader<String, X509CRL>() {
public X509CRL load(String crlURL) throws CertificateException, CRLException, NoSuchProviderException, NoSuchParserException, StreamParsingException, MalformedURLException, IOException, ExecutionException {
X509CRL result = requestCRL(crlURL);
Preconditions.checkNotNull(result);
return result;
}
};
this.crlCache = CacheBuilder.newBuilder().maximumSize(10).expireAfterWrite(60, TimeUnit.MINUTES).build(checkedLoader);
}
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);
}
}
static void test_create_signature_x509_crt_crl() throws Exception {
System.out.println("* Generating signature-x509-crt-crl.xml");
List<Object> xds = new ArrayList<>();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
xds.add(signingCert);
FileInputStream fis = new FileInputStream(CRL);
X509CRL crl = (X509CRL) cf.generateCRL(fis);
fis.close();
xds.add(crl);
KeyInfo crt_crl = kifac.newKeyInfo(Collections.singletonList
(kifac.newX509Data(xds)));
test_create_signature_external(dsaSha1, crt_crl, signingKey,
new X509KeySelector(ks), false);
System.out.println();
}
private Collection<X509CRL> loadFromURI(CertificateFactory cf, URI remoteURI) throws GeneralSecurityException {
try {
logger.debugf("Loading CRL from %s", remoteURI.toString());
URLConnection conn = remoteURI.toURL().openConnection();
conn.setDoInput(true);
conn.setUseCaches(false);
X509CRL crl = loadFromStream(cf, conn.getInputStream());
return Collections.singleton(crl);
}
catch(IOException ex) {
logger.errorf(ex.getMessage());
}
return Collections.emptyList();
}
/**
* Returns CRLs described in a X509Certificate's CRLDistributionPoints
* Extension. Only those containing a general name of type URI are read.
*/
public static List<CRL> readCRLsFromCert(X509Certificate cert)
throws Exception {
List<CRL> crls = new ArrayList<>();
CRLDistributionPointsExtension ext =
X509CertImpl.toImpl(cert).getCRLDistributionPointsExtension();
if (ext == null) return crls;
List<DistributionPoint> distPoints =
ext.get(CRLDistributionPointsExtension.POINTS);
for (DistributionPoint o: distPoints) {
GeneralNames names = o.getFullName();
if (names != null) {
for (GeneralName name: names.names()) {
if (name.getType() == GeneralNameInterface.NAME_URI) {
URIName uriName = (URIName)name.getName();
for (CRL crl: loadCRLs(uriName.getName())) {
if (crl instanceof X509CRL) {
crls.add((X509CRL)crl);
}
}
break; // Different name should point to same CRL
}
}
}
}
return crls;
}
public static String getPEMEncodedString(X509CRL holder)
throws SCMSecurityException {
try {
StringWriter stringWriter = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
pemWriter.writeObject(holder);
}
return stringWriter.toString();
} catch (IOException e) {
throw new SCMSecurityException("PEM Encoding failed for CRL." +
holder.getIssuerDN().toString(), e);
}
}
/**
* Construct an initialized PKCS7 block.
*
* @param digestAlgorithmIds the message digest algorithm identifiers.
* @param contentInfo the content information.
* @param certificates an array of X.509 certificates.
* @param crls an array of CRLs
* @param signerInfos an array of signer information.
*/
public PKCS7(AlgorithmId[] digestAlgorithmIds,
ContentInfo contentInfo,
X509Certificate[] certificates,
X509CRL[] crls,
SignerInfo[] signerInfos) {
version = BigInteger.ONE;
this.digestAlgorithmIds = digestAlgorithmIds;
this.contentInfo = contentInfo;
this.certificates = certificates;
this.crls = crls;
this.signerInfos = signerInfos;
}
protected static void processCRLI(
Date validDate,
X509CRL deltacrl,
Object cert,
CertStatus certStatus,
PKIXExtendedParameters pkixParams)
throws AnnotatedException
{
if (pkixParams.isUseDeltasEnabled() && deltacrl != null)
{
CertPathValidatorUtilities.getCertStatus(validDate, deltacrl, cert, certStatus);
}
}
/**
* Returned the encoding of the given certificate for internal use.
* Callers must guarantee that they neither modify it nor expose it
* to untrusted code. Uses getEncodedInternal() if the certificate
* is instance of X509CertImpl, getEncoded() otherwise.
*/
public static byte[] getEncodedInternal(X509CRL crl) throws CRLException {
if (crl instanceof X509CRLImpl) {
return ((X509CRLImpl)crl).getEncodedInternal();
} else {
return crl.getEncoded();
}
}
/**
* Utility method to convert an arbitrary instance of X509CRL
* to a X509CRLImpl. Does a cast if possible, otherwise reparses
* the encoding.
*/
public static X509CRLImpl toImpl(X509CRL crl)
throws CRLException {
if (crl instanceof X509CRLImpl) {
return (X509CRLImpl)crl;
} else {
return X509Factory.intern(crl);
}
}
/**
* Construct an initialized PKCS7 block.
*
* @param digestAlgorithmIds the message digest algorithm identifiers.
* @param contentInfo the content information.
* @param certificates an array of X.509 certificates.
* @param crls an array of CRLs
* @param signerInfos an array of signer information.
*/
public PKCS7(AlgorithmId[] digestAlgorithmIds,
ContentInfo contentInfo,
X509Certificate[] certificates,
X509CRL[] crls,
SignerInfo[] signerInfos) {
version = BigInteger.ONE;
this.digestAlgorithmIds = digestAlgorithmIds;
this.contentInfo = contentInfo;
this.certificates = certificates;
this.crls = crls;
this.signerInfos = signerInfos;
}
/**
* 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));
}
@Override
public X509CRL fetch(final Object crl) throws Exception {
final Set<X509CRL> results = fetch(Collections.singleton(crl));
if (results.size() > 0) {
return results.iterator().next();
}
logger.warn("Unable to fetch {}", crl);
return null;
}
private void transverseDirToFindContent(
File dir,
Collection contentList,
String[] certsFilesExts,
String[] crlsFilesExts,
CertificateFactory cf) throws CertificateException, CRLException
{
File[] dirContents = dir.listFiles();
for (int i = 0; i < dirContents.length; i++)
{
File f = dirContents[i];
if (f.isDirectory())
transverseDirToFindContent(f, contentList, certsFilesExts, crlsFilesExts, cf);
else if (f.isFile())
try
{
if (hasExt(f, certsFilesExts))
contentList.add((X509Certificate)cf.generateCertificate(new FileInputStream(f)));
else if (hasExt(f, crlsFilesExts))
contentList.add((X509CRL)cf.generateCRL(new FileInputStream(f)));
} catch (FileNotFoundException ex)
{
// The file existed right up there! If somehow it doesn't exist
// now, nevermind.
}
}
}
/**
* 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 checkSignatureValue(final X509CRL x509CRL, final CertificateToken issuerToken, final CRLValidity crlValidity) {
try {
x509CRL.verify(issuerToken.getPublicKey());
crlValidity.setSignatureIntact(true);
crlValidity.setIssuerToken(issuerToken);
} catch (GeneralSecurityException e) {
String msg = String.format("CRL Signature cannot be validated : %s", e.getMessage());
if (LOG.isTraceEnabled()) {
LOG.trace(msg, e);
} else {
LOG.warn(msg);
}
crlValidity.setSignatureInvalidityReason(msg);
}
}
/**
* Returns CRLs described in a X509Certificate's CRLDistributionPoints
* Extension. Only those containing a general name of type URI are read.
*/
public static List<CRL> readCRLsFromCert(X509Certificate cert)
throws Exception {
List<CRL> crls = new ArrayList<>();
CRLDistributionPointsExtension ext =
X509CertImpl.toImpl(cert).getCRLDistributionPointsExtension();
if (ext == null) return crls;
List<DistributionPoint> distPoints =
ext.get(CRLDistributionPointsExtension.POINTS);
for (DistributionPoint o: distPoints) {
GeneralNames names = o.getFullName();
if (names != null) {
for (GeneralName name: names.names()) {
if (name.getType() == GeneralNameInterface.NAME_URI) {
URIName uriName = (URIName)name.getName();
for (CRL crl: loadCRLs(uriName.getName())) {
if (crl instanceof X509CRL) {
crls.add((X509CRL)crl);
}
}
break; // Different name should point to same CRL
}
}
}
}
return crls;
}
/**
* Utility method to convert an arbitrary instance of X509CRL
* to a X509CRLImpl. Does a cast if possible, otherwise reparses
* the encoding.
*/
public static X509CRLImpl toImpl(X509CRL crl)
throws CRLException {
if (crl instanceof X509CRLImpl) {
return (X509CRLImpl)crl;
} else {
return X509Factory.intern(crl);
}
}
/**
* Construct an initialized PKCS7 block.
*
* @param digestAlgorithmIds the message digest algorithm identifiers.
* @param contentInfo the content information.
* @param certificates an array of X.509 certificates.
* @param crls an array of CRLs
* @param signerInfos an array of signer information.
*/
public PKCS7(AlgorithmId[] digestAlgorithmIds,
ContentInfo contentInfo,
X509Certificate[] certificates,
X509CRL[] crls,
SignerInfo[] signerInfos) {
version = BigInteger.ONE;
this.digestAlgorithmIds = digestAlgorithmIds;
this.contentInfo = contentInfo;
this.certificates = certificates;
this.crls = crls;
this.signerInfos = signerInfos;
}
/**
* Construct an initialized PKCS7 block.
*
* @param digestAlgorithmIds the message digest algorithm identifiers.
* @param contentInfo the content information.
* @param certificates an array of X.509 certificates.
* @param crls an array of CRLs
* @param signerInfos an array of signer information.
*/
public PKCS7(AlgorithmId[] digestAlgorithmIds,
ContentInfo contentInfo,
X509Certificate[] certificates,
X509CRL[] crls,
SignerInfo[] signerInfos) {
version = BigInteger.ONE;
this.digestAlgorithmIds = digestAlgorithmIds;
this.contentInfo = contentInfo;
this.certificates = certificates;
this.crls = crls;
this.signerInfos = signerInfos;
}