类java.security.cert.CertPath源码实例Demo

下面列出了怎么用java.security.cert.CertPath的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: j2objc   文件: CertificateFactory3Test.java
/**
 * 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());
    }
}
 
源代码2 项目: openjdk-jdk9   文件: CertPathEncodingTest.java
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;
}
 
源代码4 项目: carbon-identity   文件: ServerCrypto.java
@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;
}
 
源代码5 项目: openjdk-jdk9   文件: JarSigner.java
/**
 * 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);
    }
}
 
源代码7 项目: RipplePower   文件: CertificateFactory.java
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;
}
 
源代码9 项目: RipplePower   文件: RFC3280CertPathUtilities.java
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;
}
 
源代码10 项目: keystore-explorer   文件: X509CertUtil.java
/**
 * 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);
	}
}
 
源代码11 项目: webauthn4j   文件: CertPathSerializerTest.java
@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);
}
 
源代码12 项目: RipplePower   文件: RFC3280CertPathUtilities.java
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;
}
 
源代码13 项目: jdk8u-jdk   文件: Timestamp.java
/**
 * 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;
}
 
源代码14 项目: mollyim-android   文件: SigningCertificate.java
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);
  }
}
 
源代码15 项目: jdk1.8-source-analysis   文件: Timestamp.java
/**
 * 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;
}
 
源代码16 项目: jdk8u-dev-jdk   文件: SignerInfo.java
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;
}
 
源代码17 项目: j2objc   文件: CertificateFactory1Test.java
/**
 * 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());
    }
}
 
源代码18 项目: JDKSourceCode1.8   文件: Timestamp.java
/**
 * 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;
}
 
源代码19 项目: openjdk-jdk9   文件: CertUtils.java
/**
 * 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));
}
 
源代码20 项目: ripple-lib-java   文件: RFC3280CertPathUtilities.java
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);
    }
}
 
源代码21 项目: openjdk-jdk8u   文件: BuildEEBasicConstraints.java
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");
    }
}
 
源代码22 项目: jdk8u-jdk   文件: NoExtensions.java
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());
    }
 
源代码23 项目: dragonwell8_jdk   文件: NoExtensions.java
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());
    }
 
源代码24 项目: RipplePower   文件: RFC3280CertPathUtilities.java
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;
}
 
源代码25 项目: dragonwell8_jdk   文件: CertUtils.java
/**
 * 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));
}
 
源代码26 项目: jdk8u60   文件: CertUtils.java
/**
 * 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));
}
 
源代码27 项目: TencentKona-8   文件: NoExtensions.java
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());
    }
 
源代码28 项目: openjdk-8   文件: CertUtils.java
/**
 * 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));
}
 
源代码29 项目: jdk8u-jdk   文件: BuildEEBasicConstraints.java
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");
    }
}
 
源代码30 项目: signer   文件: Base64Utils.java
/**
 *
 * 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;
}
 
 类所在包
 同包方法