Java java.security.cert.CertStore 代码实例

・22 分钟阅读

以下是展示如何使用java.security.cert.CertStore的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public static void initCertPathSSCertChain() throws CertificateException,
            InvalidAlgorithmParameterException, NoSuchAlgorithmException,
            IOException {
        // create certificates and CRLs
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bi = new ByteArrayInputStream(rootCert.getBytes());
        rootCertificateSS = (X509Certificate) cf.generateCertificate(bi);
        bi = new ByteArrayInputStream(endCert.getBytes());
        endCertificate = (X509Certificate) cf.generateCertificate(bi);
        BigInteger revokedSerialNumber = BigInteger.valueOf(1);
        crl = new MyCRL("X.509");
//        X509CRL rootCRL = X509CRL;
//        X509CRL interCRL = X509CRLExample.createCRL(interCert, interPair
//                .getPrivate(), revokedSerialNumber);
        // create CertStore to support path building
        List<Object> list = new ArrayList<Object>();
        list.add(rootCertificateSS);
        list.add(endCertificate);
        CollectionCertStoreParameters params = new CollectionCertStoreParameters(
                list);
        store = CertStore.getInstance("Collection", params);
        theCertSelector = new X509CertSelector();
        theCertSelector.setCertificate(endCertificate);
        theCertSelector.setIssuer(endCertificate.getIssuerX500Principal()
                .getEncoded());
        // build the path
        builder = CertPathBuilder.getInstance("PKIX");
    }
 

实例 2


private boolean verifyAgainstCA(X509Certificate[] caCertificates, CertStore certs,
        Provider provider) throws CertStoreException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, CertificateException, CertPathValidatorException
{
    List<Certificate> certChain = new ArrayList<Certificate>();
    if (caCertificates.length > 0)
    {
        X509Certificate rootCert = caCertificates[0];
        certChain.add(rootCert);
    }
    for (int i = 1; i < caCertificates.length; i++)
    {
        certChain.add(caCertificates[i]);
    }
    Collection<? extends Certificate> certCollection = certs.getCertificates(null);
    for (Certificate c : certCollection)
    {
        certChain.add(c);
    }
    CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(certChain);
    CertStore store = CertStore.getInstance("Collection", ccsp);
    CertPath cp = CertificateFactory.getInstance("X.509", provider).generateCertPath(certChain);
    Set<TrustAnchor> trust = new HashSet<TrustAnchor>();
    trust.add(new TrustAnchor((X509Certificate) certChain.get(0), null));
    PKIXParameters param = new PKIXParameters(trust);
    param.addCertStore(store);
    param.setRevocationEnabled(false);
    param.setTrustAnchors(trust);
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX", provider);
    cpv.validate(cp, param);
    return true;
}
 

实例 3


private MimeBodyPart signMessage(MimeBodyPart bodyPart) throws Exception{
        X509Certificate cert = partnershipDVO.getVerifyX509Certificate();
        /* Create the SMIMESignedGenerator */
       SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
       capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
       capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
       capabilities.addCapability(SMIMECapability.dES_CBC);
       ASN1EncodableVector attributes = new ASN1EncodableVector();
       attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
           new IssuerAndSerialNumber(new X509Name(cert.getIssuerDN().getName()), cert.getSerialNumber()))
       );
       attributes.add(new SMIMECapabilitiesAttribute(capabilities));
       SMIMESignedGenerator signer = new SMIMESignedGenerator();
       signer.setContentTransferEncoding("base64");
       signer.addSigner(keyMan.getPrivateKey(), partnershipDVO.getVerifyX509Certificate(),
                SMIMESignedGenerator.DIGEST_SHA1,
           new AttributeTable(attributes), null);
       // Add the list of certs to the generator
       ArrayList certList = new ArrayList();
       certList.add(cert);
       CertStore certs = CertStore.getInstance("Collection",
               new CollectionCertStoreParameters(certList), "BC");
       signer.addCertificatesAndCRLs(certs);
       // Sign body part
       MimeMultipart mm = signer.generate(bodyPart, "BC");
       InternetHeaders headers = new InternetHeaders();
       boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext","true")).booleanValue();
       headers.setHeader("Content-Type", isContentTypeFolded? mm.getContentType():mm.getContentType().replaceAll("s", " "));
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       mm.writeTo(baos);  
       MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray());
       return signedPart;
}
 

实例 4


@Test
public void mySigneddataGenerator() throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, CertStoreException, CMSException,
        NoSuchProviderException, IOException
{
    byte[] hash = "01234567890123456789".getBytes();
    MyCMSSignedDataGenerator myCmsSignedDataGenerator = new MyCMSSignedDataGenerator();
    myCmsSignedDataGenerator.addSigner(privateKey, certificate, CMSSignedGenerator.DIGEST_SHA1);
    CMSProcessableByteArray cmsProcessableByteArray = new CMSProcessableByteArray(hash);
    List<Certificate> certList = new ArrayList<Certificate>();
    certList.add(certificate);
    CertStore certStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(certList), provider);
    myCmsSignedDataGenerator.addCertificatesAndCRLs(certStore);
    myCmsSignedDataGenerator.setHash(hash);
    CMSSignedData cmsSignedData = myCmsSignedDataGenerator.generate(cmsProcessableByteArray,
            provider);
    String base64Result = Base64.encodeBytes(cmsSignedData.getEncoded());
    Assert.assertTrue(base64Result != null && base64Result.length() > 0);
}
 

实例 5


CertStore createCertStore(
    String type,
    Provider provider,
    ASN1Set certSet,
    ASN1Set crlSet)
    throws CMSException, NoSuchAlgorithmException
{
    List certsAndcrls = new ArrayList();
    //
    // load the certificates and revocation lists if we have any
    //
    if (certSet != null)
    {
        addCertsFromSet(certsAndcrls, certSet, provider);
    }
    if (crlSet != null)
    {
        addCRLsFromSet(certsAndcrls, crlSet, provider);
    }
    try
    {
        if (provider != null)
        {
            return CertStore.getInstance(type, new CollectionCertStoreParameters(certsAndcrls), provider);
        }
        else
        {
            return CertStore.getInstance(type, new CollectionCertStoreParameters(certsAndcrls));
        }
    }
    catch (InvalidAlgorithmParameterException e)
    {
        throw new CMSException("can't setup the CertStore", e);
    }
}
 

实例 6


CertStore createCertStore(
    String type,
    Provider provider,
    ASN1Set certSet,
    ASN1Set crlSet)
    throws CMSException, NoSuchAlgorithmException
{
    List certsAndcrls = new ArrayList();
    //
    // load the certificates and revocation lists if we have any
    //
    if (certSet != null)
    {
        addCertsFromSet(certsAndcrls, certSet, provider);
    }
    if (crlSet != null)
    {
        addCRLsFromSet(certsAndcrls, crlSet, provider);
    }
    try
    {
        if (provider != null)
        {
            return CertStore.getInstance(type, new CollectionCertStoreParameters(certsAndcrls), provider);
        }
        else
        {
            return CertStore.getInstance(type, new CollectionCertStoreParameters(certsAndcrls));
        }
    }
    catch (InvalidAlgorithmParameterException e)
    {
        throw new CMSException("can't setup the CertStore", e);
    }
}
 

实例 7


static CertStore createCertStoreInstance(String type, CertStoreParameters params, String provider)
    throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException
{
    if (provider == null)
    {
        return CertStore.getInstance(type, params);
    }
    return CertStore.getInstance(type, params, provider);
}
 

实例 8


/**
 * Creates <code>List</code> of <code>CollectionCertStores</code>
 *
 * @return The list created
 *
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchAlgorithmException
 */
public static List<CertStore> getCollectionCertStoresList()
    throws InvalidAlgorithmParameterException,
           NoSuchAlgorithmException {
    CertStore cs = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters());
    ArrayList<CertStore> l = new ArrayList<CertStore>();
    if (!l.add(cs)) {
        throw new RuntimeException("Could not create cert stores list");
    }
    return l;
}
 

实例 9


private MimeBodyPart signMessage(MimeBodyPart bodyPart) throws Exception{
        X509Certificate cert = partnershipDVO.getVerifyX509Certificate();
        /* Create the SMIMESignedGenerator */
       SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
       capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
       capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
       capabilities.addCapability(SMIMECapability.dES_CBC);
       ASN1EncodableVector attributes = new ASN1EncodableVector();
       attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
           new IssuerAndSerialNumber(new X509Name(cert.getIssuerDN().getName()), cert.getSerialNumber()))
       );
       attributes.add(new SMIMECapabilitiesAttribute(capabilities));
       SMIMESignedGenerator signer = new SMIMESignedGenerator();
       signer.setContentTransferEncoding("base64");
       signer.addSigner(keyMan.getPrivateKey(), partnershipDVO.getVerifyX509Certificate(),
                SMIMESignedGenerator.DIGEST_SHA1,
           new AttributeTable(attributes), null);
       // Add the list of certs to the generator
       ArrayList certList = new ArrayList();
       certList.add(cert);
       CertStore certs = CertStore.getInstance("Collection",
               new CollectionCertStoreParameters(certList), "BC");
       signer.addCertificatesAndCRLs(certs);
       // Sign body part
       MimeMultipart mm = signer.generate(bodyPart, "BC");
       InternetHeaders headers = new InternetHeaders();
       boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext","true")).booleanValue();
       headers.setHeader("Content-Type", isContentTypeFolded? mm.getContentType():mm.getContentType().replaceAll("s", " "));
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       mm.writeTo(baos);  
       MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray());
       return signedPart;
}
 

实例 10


public void sign(X509Certificate cert, PrivateKey privateKey, String digestAlg) throws SFRMException {
    try {
        /* Create the SMIMESignedGenerator */
        SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
        capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
        capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
        capabilities.addCapability(SMIMECapability.dES_CBC);
        SMIMESignedGenerator signer = new SMIMESignedGenerator();
        signer.setContentTransferEncoding("binary");
        if (digestAlg.equalsIgnoreCase(ALG_SIGN_MD5))
                signer.addSigner(privateKey, cert, SMIMESignedGenerator.DIGEST_MD5);
        else if (digestAlg.equalsIgnoreCase(ALG_SIGN_SHA1))
                signer.addSigner(privateKey, cert, SMIMESignedGenerator.DIGEST_SHA1);
        else
                throw new SFRMException("Encryption algorithm error - " + digestAlg);
        /* Add the list of certs to the generator */
        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(certList), "BC");
        signer.addCertificatesAndCRLs(certs);
        /* Sign the body part */
        MimeMultipart mm = signer.generate(bodyPart, "BC");
        InternetHeaders headers = new InternetHeaders();
        headers.setHeader("Content-Type", mm.getContentType());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mm.writeTo(baos);
        this.bodyPart = new MimeBodyPart(headers, baos.toByteArray());
        this.setIsSigned(true);
    } catch (org.bouncycastle.mail.smime.SMIMEException ex) {
        throw new SFRMException("Unable to sign body part", ex.getUnderlyingException());
    } catch (Exception e) {
        throw new SFRMException("Unable to sign body part", e);
    }
}
 

实例 11


@Test
public void validateGsi2PathGood() throws Exception {
    KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]});
    TestCertParameters parameters = new TestCertParameters(null, this.crls);
    CertStore certStore = CertStore.getInstance("MockCertStore", parameters);
    TestPolicyStore policyStore = new TestPolicyStore(null);
    // EEC, CA
    List<Certificate> tmpCerts = new Vector<Certificate>();
    tmpCerts.add(goodCertsArr[1]);
    tmpCerts.add(goodCertsArr[0]);
    CertPath certPath = factory.generateCertPath(tmpCerts);
    validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], false);
    // proxy, EEC, CA
    tmpCerts.clear();
    tmpCerts.add(goodCertsArr[2]);
    tmpCerts.add(goodCertsArr[1]);
    tmpCerts.add(goodCertsArr[0]);
    certPath = factory.generateCertPath(tmpCerts);
    validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], false);
    // limited proxy, EEC, CA
    tmpCerts.clear();
    tmpCerts.add(goodCertsArr[3]);
    tmpCerts.add(goodCertsArr[1]);
    tmpCerts.add(goodCertsArr[0]);
    certPath = factory.generateCertPath(tmpCerts);
    validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], true);
    // double limited proxy, limited proxy, EEC, CA
    tmpCerts.clear();
    tmpCerts.add(goodCertsArr[4]);
    tmpCerts.add(goodCertsArr[3]);
    tmpCerts.add(goodCertsArr[1]);
    tmpCerts.add(goodCertsArr[0]);
    certPath = factory.generateCertPath(tmpCerts);
    validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], true);
}
 

实例 12


@Test
public void validatePathBad() throws Exception {
    KeyStore keyStore = getKeyStore(null);
    X509Certificate[] chain;
    CertStore certStore = CertStore.getInstance("MockCertStore", null);
    TestPolicyStore policyStore = new TestPolicyStore(null);
    // proxy, CA
    chain = new X509Certificate[]{goodCertsArr[5], goodCertsArr[0]};
    validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path");
    // user, proxy, CA
    chain = new X509Certificate[]{goodCertsArr[1], goodCertsArr[2], goodCertsArr[0]};
    validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path");
    // user, user, CA
    chain = new X509Certificate[]{goodCertsArr[1], goodCertsArr[1], goodCertsArr[0]};
    validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path");
    // user, CA, user
    chain = new X509Certificate[]{goodCertsArr[1], goodCertsArr[0], goodCertsArr[1]};
    validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path");
}
 

实例 13


private static List findCerts(List certStores, X509CertSelector selector)
        throws CertStoreException
{
    List result = new ArrayList();
    Iterator it = certStores.iterator();
    while (it.hasNext())
    {
        CertStore store = (CertStore) it.next();
        Collection coll = store.getCertificates(selector);
        result.addAll(coll);
    }
    return result;
}
 

实例 14


public Collection engineGetCertificates(CertSelector certSelector)
    throws CertStoreException
{
    boolean searchAllStores = params.getSearchAllStores();
    Iterator iter = params.getCertStores().iterator();
    List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST;
    while (iter.hasNext())
    {
        CertStore store = (CertStore)iter.next();
        Collection certs = store.getCertificates(certSelector);
        if (searchAllStores)
        {
            allCerts.addAll(certs);
        }
        else if (!certs.isEmpty())
        {
            return certs;
        }
    }
    return allCerts;
}
 

实例 15


public Collection engineGetCertificates(CertSelector certSelector)
    throws CertStoreException
{
    boolean searchAllStores = params.getSearchAllStores();
    Iterator iter = params.getCertStores().iterator();
    List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST;
    while (iter.hasNext())
    {
        CertStore store = (CertStore)iter.next();
        Collection certs = store.getCertificates(certSelector);
        if (searchAllStores)
        {
            allCerts.addAll(certs);
        }
        else if (!certs.isEmpty())
        {
            return certs;
        }
    }
    return allCerts;
}
 
讨论
淘淘あ西西 profile image