Example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider.

Prototype

public BouncyCastleProvider() 

Source Link

Document

Construct a new provider.

Usage

From source file:br.gov.frameworkdemoiselle.certificate.signer.util.ValidadorUtil.java

License:Open Source License

/**
 * Valida uma assinatura digital ou um certificado digital tomando por base
 * o certificado raiz da ICP-Brasil//from w w  w . j  a va 2  s  . c  o m
 *
 * @param contentSigned
 * @param trustedCa
 * @param encoding
 * @throws SignerException
 */
public static void validate(byte[] contentSigned, String policyOID, CertPathEncoding encoding)
        throws SignerException {
    X509Certificate userCertificate = null;
    Collection<X509Certificate> trustedCas = CAManager.getInstance().getSignaturePolicyRootCAs(policyOID);
    try {

        CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
        InputStream in = new ByteArrayInputStream(new byte[512]);

        Security.addProvider(new BouncyCastleProvider());
        in = new ByteArrayInputStream(contentSigned);
        CertPath certPath = null;

        switch (encoding) {
        case PKCS7:
            certPath = factory.generateCertPath(in, "PKCS7");
            break;

        case PkiPath:
            certPath = factory.generateCertPath(in, "PkiPath");
            break;
        }

        userCertificate = (X509Certificate) certPath.getCertificates().iterator().next();

        // Carrega os certificados confiaveis
        List<TrustAnchor> trustAnchors = new ArrayList<TrustAnchor>();
        for (X509Certificate x : trustedCas) {
            trustAnchors.add(new TrustAnchor(x, null));
        }

        Set trust = new HashSet();
        Collections.addAll(trust, trustAnchors.toArray());

        // Create the parameters for the validator
        PKIXParameters params = new PKIXParameters(trust);

        params.setSigProvider("BC");
        params.setRevocationEnabled(false);
        CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
        CertPathValidatorResult result = certPathValidator.validate(certPath, params);

        // Get the CA used to validate this path
        PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
        TrustAnchor trustAnchor = pkixResult.getTrustAnchor();
        X509Certificate cert = trustAnchor.getTrustedCert();

    } catch (Throwable error) {
        error.printStackTrace();
        //            if (error.getCause() instanceof CertificateExpiredException) {
        //                throw new SignerException("O certificado de uma das cadeias est expirado", error);
        //            }

        try {
            CAManager.getInstance().validateRootCAs(trustedCas, userCertificate);
        } catch (Throwable managerError) {
            managerError.printStackTrace();
            throw new SignerException("Este certificado nao esta associado a uma cadeia confiavel de ACs",
                    error);
        }
    }
}

From source file:br.gov.jfrj.siga.cd.service.impl.CdServiceImplTest.java

License:Open Source License

@Override
protected void setUp() throws Exception {
    this.bouncyCastleProvider = (BouncyCastleProvider) Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
    if (this.bouncyCastleProvider == null) {
        this.bouncyCastleProvider = new BouncyCastleProvider();
        Security.addProvider(this.bouncyCastleProvider);
    }//from  ww  w .j  av  a 2 s.com
    super.setUp();
}

From source file:brooklyn.util.crypto.SecureKeys.java

License:Apache License

public static KeyPair readPem(InputStream input, final String passphrase) {
    try {//from  w ww. j av a  2 s  .co  m
        Security.addProvider(new BouncyCastleProvider());
        PEMReader pr = new PEMReader(new InputStreamReader(input), new PasswordFinder() {
            public char[] getPassword() {
                return passphrase != null ? passphrase.toCharArray() : new char[0];
            }
        });
        KeyPair result = (KeyPair) pr.readObject();
        pr.close();
        return result;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:CA.InternalCA.java

License:Apache License

public InternalCA() {
    // initialize BouncyCastle
    Security.addProvider(new BouncyCastleProvider());
    LOG.info("Initialized BouncyCastle...");
}

From source file:ca.nrc.cadc.cred.CertUtil.java

License:Open Source License

/**
 * Method that generates an X509 proxy certificate
 * // w ww  .  j av  a2 s  .  c  o  m
 * @param csr CSR for the certificate
 * @param lifetime lifetime of the certificate in SECONDS
 * @param chain certificate used to sign the proxy certificate
 * @return generated proxy certificate
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CertificateParsingException
 * @throws CertificateEncodingException
 * @throws SignatureException
 * @throws CertificateNotYetValidException
 * @throws CertificateExpiredException
 */
public static X509Certificate generateCertificate(PKCS10CertificationRequest csr, int lifetime,
        X509CertificateChain chain) throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, CertificateParsingException, CertificateEncodingException, SignatureException,
        CertificateExpiredException, CertificateNotYetValidException {
    X509Certificate issuerCert = chain.getChain()[0];
    PrivateKey issuerKey = chain.getPrivateKey();

    Security.addProvider(new BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(issuerCert.getSubjectX500Principal());

    // generate the proxy DN as the issuerDN + CN=random number
    Random rand = new Random();
    String issuerDN = issuerCert.getSubjectX500Principal().getName(X500Principal.RFC2253);
    String delegDN = String.valueOf(Math.abs(rand.nextInt()));
    String proxyDn = "CN=" + delegDN + "," + issuerDN;
    certGen.setSubjectDN(new X500Principal(proxyDn));

    // set validity
    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    // Start date. Allow for a sixty five minute clock skew here.
    date.add(Calendar.MINUTE, -65);
    Date beforeDate = date.getTime();
    for (X509Certificate currentCert : chain.getChain()) {
        if (beforeDate.before(currentCert.getNotBefore())) {
            beforeDate = currentCert.getNotBefore();
        }
    }
    certGen.setNotBefore(beforeDate);

    // End date.
    // If hours = 0, then cert lifetime is set to that of user cert
    if (lifetime <= 0) {
        // set the validity of certificates as the minimum
        // of the certificates in the chain
        Date afterDate = issuerCert.getNotAfter();
        for (X509Certificate currentCert : chain.getChain()) {
            if (afterDate.after(currentCert.getNotAfter())) {
                afterDate = currentCert.getNotAfter();
            }
        }
        certGen.setNotAfter(afterDate);
    } else {
        // check the validity of the signing certificate
        date.add(Calendar.MINUTE, 5);
        date.add(Calendar.SECOND, lifetime);
        for (X509Certificate currentCert : chain.getChain()) {
            currentCert.checkValidity(date.getTime());
        }

        certGen.setNotAfter(date.getTime());
    }

    certGen.setPublicKey(csr.getPublicKey());
    // TODO: should be able to get signature algorithm from the csr, but... obtuse
    certGen.setSignatureAlgorithm(DEFAULT_SIGNATURE_ALGORITHM);

    // extensions
    // add ProxyCertInfo extension to the new cert

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(issuerCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    // add the Proxy Certificate Information
    // I expect this code to be removed once support to proxy
    // certificates is provided in Bouncy Castle.

    // create a proxy policy
    // types of proxy certificate policies - see RFC3820
    // impersonates the user
    final DERObjectIdentifier IMPERSONATION = new DERObjectIdentifier("1.3.6.1.5.5.7.21.1");
    // independent
    // final DERObjectIdentifier INDEPENDENT = new
    // DERObjectIdentifier(
    // "1.3.6.1.5.5.7.21.2");
    // defined by a policy language
    // final DERObjectIdentifier LIMITED = new DERObjectIdentifier(
    // "1.3.6.1.4.1.3536.1.1.1.9");

    ASN1EncodableVector policy = new ASN1EncodableVector();
    policy.add(IMPERSONATION);

    // pathLengthConstr (RFC3820)
    // The pCPathLenConstraint field, if present, specifies the
    // maximum
    // depth of the path of Proxy Certificates that can be signed by
    // this
    // Proxy Certificate. A pCPathLenConstraint of 0 means that this
    // certificate MUST NOT be used to sign a Proxy Certificate. If
    // the
    // pCPathLenConstraint field is not present then the maximum proxy
    // path
    // length is unlimited. End entity certificates have unlimited
    // maximum
    // proxy path lengths.
    // DERInteger pathLengthConstr = new DERInteger(100);

    // create the proxy certificate information
    ASN1EncodableVector vec = new ASN1EncodableVector();
    // policy.add(pathLengthConstr);
    vec.add(new DERSequence(policy));

    // OID
    final DERObjectIdentifier OID = new DERObjectIdentifier("1.3.6.1.5.5.7.1.14");
    certGen.addExtension(OID, true, new DERSequence(vec));

    return certGen.generate(issuerKey, "BC");
}

From source file:ca.nrc.cadc.cred.server.actions.DelegationAction.java

License:Open Source License

X509CertificateChain prepareCert(X509CertificateChain signCert) throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException, CertificateParsingException,
        CertificateEncodingException, CertificateExpiredException, CertificateNotYetValidException {
    log.debug("prepareCert - START");
    if (!(signCert.getPrivateKey() instanceof RSAKey)) {
        // TODO - Only RSA keys are supported. Generate a proxy cert
        // if this is not the case
        // This should probably be cached somehow
        if (daysValid == Float.MAX_VALUE) {
            daysValid = 30.0f;//  w ww. java 2s  .co m
        }
    }

    if (daysValid == Float.MAX_VALUE) {
        // return the stored certificate as it is
        log.debug("daysValid = " + daysValid + ", returning bare certificate");
        return signCert;
    } else {
        // return proxy certificate signed with the key of the
        // stored certificate

        try {

            // Add the Bouncy Castle JCE provider. This allows the CSR
            // classes to work. The BC implementation of PKCS#10 depends
            // on the ciphers in the BC provider.
            if (Security.getProvider("BC") == null) {
                Security.addProvider(new BouncyCastleProvider());
            }

            KeyPairGenerator keyPairGenerator = null;
            try {
                keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            } catch (NoSuchAlgorithmException ex) {
                ex.printStackTrace();
                throw new RuntimeException("The JCE doesn't do RSA! Game over.");
            }
            keyPairGenerator.initialize(CertUtil.DEFAULT_KEY_LENGTH);

            // generate the subject
            String subject = signCert.getChain()[0].getSubjectX500Principal().getName(X500Principal.CANONICAL);

            // generated the key pair
            KeyPair keys = keyPairGenerator.generateKeyPair();

            // generate the CSR
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                    CertUtil.DEFAULT_SIGNATURE_ALGORITHM, new X509Name(subject), keys.getPublic(), null,
                    keys.getPrivate(), "BC");
            log.debug("PKCS10CertificationRequest " + csr.getSignatureAlgorithm().toString());

            // sign the CSR
            X509Certificate newCert = CertUtil.generateCertificate(csr, Math.round(daysValid * 24 * 60 * 60),
                    signCert);

            // package and return
            X509Certificate[] certChain = new X509Certificate[signCert.getChain().length + 1];
            certChain[0] = newCert;
            System.arraycopy(signCert.getChain(), 0, certChain, 1, signCert.getChain().length);
            X509CertificateChain result = new X509CertificateChain(certChain, keys.getPrivate());
            result.setPrincipal(signCert.getPrincipal());

            return result;
        } finally {
            profiler.checkpoint("prepareCert");
        }
    }
}

From source file:ca.nrc.cadc.cred.server.DatabaseDelegations.java

License:Open Source License

protected DatabaseDelegations(String dataSourceName, CertificateDAO.CertificateSchema config) {
    // Add the Bouncy Castle JCE provider. This allows the CSR
    // classes to work. The BC implementation of PKCS#10 depends on
    // the ciphers in the BC provider.
    if (Security.getProvider("BC") == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from   w w  w  . j a  v  a  2  s. c  o m*/

    try {
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(CertUtil.DEFAULT_KEY_LENGTH);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException("BUG/CONFIG: cannot load RSA key-pair generator", ex);
    }

    certificateDAO = new CertificateDAO(config);
}

From source file:ca.trustpoint.m2m.DigicertCertificates1.java

License:Apache License

@Before
public void createSharedVariables() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:ca.trustpoint.m2m.DigicertCertificates2.java

License:Apache License

@Before
public void createSharedVariables() {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:ca.trustpoint.m2m.M2mCertificateTest.java

License:Apache License

@BeforeClass
public static void initializeTests() {
    Security.addProvider(new BouncyCastleProvider());
}