下面列出了怎么用java.security.cert.CertPath的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Test for <code>generateCertPath(List certificates)</code> method
* Assertion: returns CertPath with 1 Certificate
*/
public void testGenerateCertPath01() throws Exception {
CertificateFactory[] certFs = initCertFs();
assertNotNull("CertificateFactory objects were not created", certFs);
// create list of certificates with one certificate
Certificate cert = certFs[0]
.generateCertificate(new ByteArrayInputStream(TestUtils
.getEncodedX509Certificate()));
List<Certificate> list = new Vector<Certificate>();
list.add(cert);
for (int i = 0; i < certFs.length; i++) {
CertPath certPath = null;
certPath = certFs[i].generateCertPath(list);
assertEquals(cert.getType(), certPath.getType());
List<? extends Certificate> list1 = certPath.getCertificates();
assertFalse("Result list is empty", list1.isEmpty());
Iterator<? extends Certificate> it = list1.iterator();
assertEquals("Incorrect Certificate in CertPath", cert, it.next());
}
}
public static void main(String[] args) throws Exception {
// Make the CertPath whose encoded form has already been stored
CertificateFactory certFac = CertificateFactory.getInstance("X509");
final List<Certificate> certs = new ArrayList<>();
certs.add(certFac.generateCertificate(new ByteArrayInputStream(cert1.getBytes())));
certs.add(certFac.generateCertificate(new ByteArrayInputStream(cert2.getBytes())));
CertPath cp = certFac.generateCertPath(certs);
// Get the encoded form of the CertPath we made
byte[] encoded = cp.getEncoded("PKCS7");
// check if it matches the encoded value
if (!Arrays.equals(encoded, Base64.getMimeDecoder().decode(pkcs7path.getBytes()))) {
throw new RuntimeException("PKCS#7 encoding doesn't match stored value");
}
// Generate a CertPath from the encoded value and check if it equals
// the CertPath generated from the certificates
CertPath decodedCP = certFac.generateCertPath(new ByteArrayInputStream(encoded), "PKCS7");
if (!decodedCP.equals(cp)) {
throw new RuntimeException("CertPath decoded from PKCS#7 isn't equal to original");
}
}
protected static int prepareNextCertL(
CertPath certPath,
int index,
int maxPathLength)
throws CertPathValidatorException
{
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate)certs.get(index);
//
// (l)
//
if (!CertPathValidatorUtilities.isSelfIssued(cert))
{
if (maxPathLength <= 0)
{
throw new ExtCertPathValidatorException("Max path length not greater than zero", null, certPath, index);
}
return maxPathLength - 1;
}
return maxPathLength;
}
@Override
/**
* @see org.apache.ws.security.components.crypto.Crypto#getX509Certificates(byte[], boolean)
*/
public X509Certificate[] getX509Certificates(byte[] data, boolean reverse)
throws WSSecurityException {
InputStream in = new ByteArrayInputStream(data);
CertPath path;
try {
path = getCertificateFactory().generateCertPath(in);
} catch (CertificateException e) {
throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"parseError");
}
List l = path.getCertificates();
X509Certificate[] certs = new X509Certificate[l.size()];
Iterator iterator = l.iterator();
for (int i = 0; i < l.size(); i++) {
certs[reverse ? (l.size() - 1 - i) : i] = (X509Certificate) iterator.next();
}
return certs;
}
/**
* Creates a {@code JarSigner.Builder} object with a private key and
* a certification path.
*
* @param privateKey the private key of the signer.
* @param certPath the certification path of the signer.
* @throws IllegalArgumentException if {@code certPath} is empty, or
* the {@code privateKey} algorithm does not match the algorithm
* of the {@code PublicKey} in the end entity certificate
* (the first certificate in {@code certPath}).
*/
public Builder(PrivateKey privateKey, CertPath certPath) {
List<? extends Certificate> certs = certPath.getCertificates();
if (certs.isEmpty()) {
throw new IllegalArgumentException("certPath cannot be empty");
}
if (!privateKey.getAlgorithm().equals
(certs.get(0).getPublicKey().getAlgorithm())) {
throw new IllegalArgumentException
("private key algorithm does not match " +
"algorithm of public key in end entity " +
"certificate (the 1st in certPath)");
}
this.privateKey = privateKey;
try {
this.certChain = certs.toArray(new X509Certificate[certs.size()]);
} catch (ArrayStoreException ase) {
// Wrong type, not X509Certificate.
throw new IllegalArgumentException(
"Entry does not contain X509Certificate");
}
}
protected static void processCertF(
CertPath certPath,
int index,
PKIXPolicyNode validPolicyTree,
int explicitPolicy)
throws CertPathValidatorException
{
//
// (f)
//
if (explicitPolicy <= 0 && validPolicyTree == null)
{
throw new ExtCertPathValidatorException("No valid policy tree found when one expected.", null, certPath,
index);
}
}
public CertPath engineGenerateCertPath(
List certificates)
throws CertificateException
{
Iterator iter = certificates.iterator();
Object obj;
while (iter.hasNext())
{
obj = iter.next();
if (obj != null)
{
if (!(obj instanceof X509Certificate))
{
throw new CertificateException("list contains non X509Certificate object while creating CertPath\n" + obj.toString());
}
}
}
return new PKIXCertPath(certificates);
}
public CertPathReviewerException(
ErrorBundle errorMessage,
Throwable throwable,
CertPath certPath,
int index)
{
super(errorMessage, throwable);
if (certPath == null || index == -1)
{
throw new IllegalArgumentException();
}
if (index < -1 || (certPath != null && index >= certPath.getCertificates().size()))
{
throw new IndexOutOfBoundsException();
}
this.certPath = certPath;
this.index = index;
}
protected static int prepareNextCertH2(
CertPath certPath,
int index,
int policyMapping)
{
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate)certs.get(index);
//
// (h)
//
if (!CertPathValidatorUtilities.isSelfIssued(cert))
{
//
// (2)
//
if (policyMapping != 0)
{
return policyMapping - 1;
}
}
return policyMapping;
}
/**
* PKCS #7 encode a number of certificates.
*
* @return The encoding
* @param certs
* The certificates
* @throws CryptoException
* If there was a problem encoding the certificates
*/
public static byte[] getCertsEncodedPkcs7(X509Certificate[] certs) throws CryptoException {
try {
ArrayList<Certificate> encodedCerts = new ArrayList<>();
Collections.addAll(encodedCerts, certs);
CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());
CertPath cp = cf.generateCertPath(encodedCerts);
return cp.getEncoded(PKCS7_ENCODING);
} catch (CertificateException | NoSuchProviderException e) {
throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e);
}
}
@Test
void test() throws CertificateException {
//Given
Certificate cert1 = TestAttestationUtil.loadFirefoxSWTokenAttestationCertificate();
Certificate cert2 = TestAttestationUtil.loadFirefoxSWTokenAttestationCertificate();
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
CertPath certPath = certificateFactory.generateCertPath(Arrays.asList(cert1, cert2));
byte[] result = cborConverter.writeValueAsBytes(certPath);
//When
CertPath restored = cborConverter.readValue(result, CertPath.class);
//Then
assertThat(restored.getCertificates().toArray()).containsExactly(cert1, cert2);
}
protected static int prepareNextCertL(
CertPath certPath,
int index,
int maxPathLength)
throws CertPathValidatorException
{
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate)certs.get(index);
//
// (l)
//
if (!CertPathValidatorUtilities.isSelfIssued(cert))
{
if (maxPathLength <= 0)
{
throw new ExtCertPathValidatorException("Max path length not greater than zero", null, certPath, index);
}
return maxPathLength - 1;
}
return maxPathLength;
}
/**
* Constructs a Timestamp.
*
* @param timestamp is the timestamp's date and time. It must not be null.
* @param signerCertPath is the TSA's certificate path. It must not be null.
* @throws NullPointerException if timestamp or signerCertPath is null.
*/
public Timestamp(Date timestamp, CertPath signerCertPath) {
if (timestamp == null || signerCertPath == null) {
throw new NullPointerException();
}
this.timestamp = new Date(timestamp.getTime()); // clone
this.signerCertPath = signerCertPath;
}
private void verifyDistinguishedName(CertPath path) throws CertificateException {
X509Certificate leaf = (X509Certificate) path.getCertificates().get(0);
String distinguishedName = leaf.getSubjectX500Principal().getName();
if (!"CN=Intel SGX Attestation Report Signing,O=Intel Corporation,L=Santa Clara,ST=CA,C=US".equals(distinguishedName)) {
throw new CertificateException("Bad DN: " + distinguishedName);
}
}
/**
* Constructs a Timestamp.
*
* @param timestamp is the timestamp's date and time. It must not be null.
* @param signerCertPath is the TSA's certificate path. It must not be null.
* @throws NullPointerException if timestamp or signerCertPath is null.
*/
public Timestamp(Date timestamp, CertPath signerCertPath) {
if (timestamp == null || signerCertPath == null) {
throw new NullPointerException();
}
this.timestamp = new Date(timestamp.getTime()); // clone
this.signerCertPath = signerCertPath;
}
public Timestamp getTimestamp()
throws IOException, NoSuchAlgorithmException, SignatureException,
CertificateException
{
if (timestamp != null || !hasTimestamp)
return timestamp;
if (unauthenticatedAttributes == null) {
hasTimestamp = false;
return null;
}
PKCS9Attribute tsTokenAttr =
unauthenticatedAttributes.getAttribute(
PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
if (tsTokenAttr == null) {
hasTimestamp = false;
return null;
}
PKCS7 tsToken = new PKCS7((byte[])tsTokenAttr.getValue());
// Extract the content (an encoded timestamp token info)
byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
// Extract the signer (the Timestamping Authority)
// while verifying the content
SignerInfo[] tsa = tsToken.verify(encTsTokenInfo);
// Expect only one signer
ArrayList<X509Certificate> chain = tsa[0].getCertificateChain(tsToken);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
CertPath tsaChain = cf.generateCertPath(chain);
// Create a timestamp token info object
TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
// Check that the signature timestamp applies to this signature
verifyTimestamp(tsTokenInfo);
// Create a timestamp object
timestamp = new Timestamp(tsTokenInfo.getDate(), tsaChain);
return timestamp;
}
/**
* Test for <code>generateCertPath(List certificates)</code> method
* Assertion: returns empty CertPath if certificates is empty
*/
public void testCertificateFactory15() throws CertificateException {
if (!X509Support) {
fail(NotSupportMsg);
return;
}
CertificateFactory[] certFs = initCertFs();
assertNotNull("CertificateFactory objects were not created", certFs);
List<Certificate> list = new Vector<Certificate>();
for (int i = 0; i < certFs.length; i++) {
CertPath cp = certFs[i].generateCertPath(list);
List<? extends Certificate> list1 = cp.getCertificates();
assertTrue("List should be empty", list1.isEmpty());
}
}
/**
* Constructs a Timestamp.
*
* @param timestamp is the timestamp's date and time. It must not be null.
* @param signerCertPath is the TSA's certificate path. It must not be null.
* @throws NullPointerException if timestamp or signerCertPath is null.
*/
public Timestamp(Date timestamp, CertPath signerCertPath) {
if (timestamp == null || signerCertPath == null) {
throw new NullPointerException();
}
this.timestamp = new Date(timestamp.getTime()); // clone
this.signerCertPath = signerCertPath;
}
/**
* Read a bunch of certs from files and create a CertPath 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
* @throws Exception on error
*/
public static CertPath buildPath(String relPath, String [] fileNames)
throws Exception {
List<X509Certificate> list = new ArrayList<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
list.add(0, getCertFromFile(relPath + fileNames[i]));
}
CertificateFactory cf = CertificateFactory.getInstance("X509");
return(cf.generateCertPath(list));
}
protected static void wrapupCertF(
CertPath certPath,
int index,
List pathCheckers,
Set criticalExtensions)
throws CertPathValidatorException
{
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate)certs.get(index);
Iterator tmpIter;
tmpIter = pathCheckers.iterator();
while (tmpIter.hasNext())
{
try
{
((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions);
}
catch (CertPathValidatorException e)
{
throw new ExtCertPathValidatorException("Additional certificate path checker failed.", e, certPath,
index);
}
}
if (!criticalExtensions.isEmpty())
{
throw new ExtCertPathValidatorException("Certificate has unsupported critical extension: " + criticalExtensions, null, certPath,
index);
}
}
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");
}
}
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 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());
}
protected static int prepareNextCertJ(
CertPath certPath,
int index,
int inhibitAnyPolicy)
throws CertPathValidatorException
{
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate)certs.get(index);
//
// (j)
//
ASN1Integer iap = null;
try
{
iap = ASN1Integer.getInstance(CertPathValidatorUtilities.getExtensionValue(cert,
RFC3280CertPathUtilities.INHIBIT_ANY_POLICY));
}
catch (Exception e)
{
throw new ExtCertPathValidatorException("Inhibit any-policy extension cannot be decoded.", e, certPath,
index);
}
if (iap != null)
{
int _inhibitAnyPolicy = iap.getValue().intValue();
if (_inhibitAnyPolicy < inhibitAnyPolicy)
{
return _inhibitAnyPolicy;
}
}
return inhibitAnyPolicy;
}
/**
* Read a bunch of certs from files and create a CertPath 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
* @throws Exception on error
*/
public static CertPath buildPath(String relPath, String [] fileNames)
throws Exception {
List<X509Certificate> list = new ArrayList<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
list.add(0, getCertFromFile(relPath + fileNames[i]));
}
CertificateFactory cf = CertificateFactory.getInstance("X509");
return(cf.generateCertPath(list));
}
/**
* Read a bunch of certs from files and create a CertPath 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
* @throws Exception on error
*/
public static CertPath buildPath(String relPath, String [] fileNames)
throws Exception {
List<X509Certificate> list = new ArrayList<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
list.add(0, getCertFromFile(relPath + fileNames[i]));
}
CertificateFactory cf = CertificateFactory.getInstance("X509");
return(cf.generateCertPath(list));
}
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());
}
/**
* Read a bunch of certs from files and create a CertPath 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
* @throws Exception on error
*/
public static CertPath buildPath(String relPath, String [] fileNames)
throws Exception {
List<X509Certificate> list = new ArrayList<X509Certificate>();
for (int i = 0; i < fileNames.length; i++) {
list.add(0, getCertFromFile(relPath + fileNames[i]));
}
CertificateFactory cf = CertificateFactory.getInstance("X509");
return(cf.generateCertPath(list));
}
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");
}
}
/**
*
* Performs the encoding of a certificate chain to base64
*
* @param aCertificationChain certificate chain
* @return ASN.1 DER encoded on Base64, for X.509 certificate
* @throws CertificateException exception
*/
public static String encodeX509CertChainToBase64(Certificate[] aCertificationChain) throws CertificateException {
List<Certificate> certList = Arrays.asList(aCertificationChain);
CertificateFactory certFactory = CertificateFactory.getInstance(X509_CERTIFICATE_TYPE);
CertPath certPath = certFactory.generateCertPath(certList);
byte[] certPathEncoded = certPath.getEncoded(CERTIFICATION_CHAIN_ENCODING);
String base64encodedCertChain = Base64Utils.base64Encode(certPathEncoded);
return base64encodedCertChain;
}