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

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

Introduction

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

Prototype

String PROVIDER_NAME

To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.

Click Source Link

Usage

From source file:org.cesecore.keys.util.SignWithWorkingAlgorithmTest.java

License:Open Source License

/**
 * Just checking that right algorithm is stilled picked for the BC provider.
 * @throws NoSuchProviderException//  ww w .j a v a2s .c om
 * @throws GeneralSecurityException
 * @throws TaskWithSigningException 
 */
@Test
public void n5BC1024() throws NoSuchProviderException, GeneralSecurityException, TaskWithSigningException {
    final SignOperation operation = new SignOperation(generateKeyPair(1024));
    assertTrue(
            SignWithWorkingAlgorithm.doSignTask(SIG_ALGS_RSA, BouncyCastleProvider.PROVIDER_NAME, operation));
    assertTrue(operation.verifySignature());
    assertEquals(1, operation.getNrOfCalls());
    assertEquals(AlgorithmConstants.SIGALG_SHA1_WITH_RSA_AND_MGF1, operation.getUsedAlgorithm());
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Creates Certificate from byte[], can be either an X509 certificate or a CVCCertificate
 * /*from  www . j a v a2s . c  o m*/
 * @param cert byte array containing certificate in binary (DER) format, or PEM encoded X.509 certificate
 * @param provider provider for example "SUN" or "BC", use null for the default provider (BC)
 * 
 * @return a Certificate 
 * @throws CertificateParsingException if certificate couldn't be parsed from cert
 * 
 */
public static Certificate getCertfromByteArray(byte[] cert, String provider)
        throws CertificateParsingException {
    Certificate ret = null;
    String prov = provider;
    if (provider == null) {
        prov = BouncyCastleProvider.PROVIDER_NAME;
    }
    try {
        final CertificateFactory cf = CertTools.getCertificateFactory(prov);
        ret = cf.generateCertificate(new ByteArrayInputStream(cert));
    } catch (CertificateException e) {
        log.debug("CertificateException trying to read X509Certificate.", e);
    }
    if (ret == null) {
        // We could not create an X509Certificate, see if it is a CVC certificate instead
        try {
            final CVCertificate parsedObject = CertificateParser.parseCertificate(cert);
            ret = new CardVerifiableCertificate(parsedObject);
        } catch (ParseException e) {
            log.debug("ParseException trying to read CVCCertificate.", e);
        } catch (ConstructionException e) {
            log.debug("ConstructionException trying to read CVCCertificate.", e);
        }
    }
    if (ret == null) {
        throw new CertificateParsingException(
                "No certificate could be parsed from byte array. See debug logs for details.");
    }
    return ret;
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * /* w w w.j  a v  a2 s  . co m*/
 * @throws CertificateParsingException if the byte array does not contain a proper certificate.
 */
public static Certificate getCertfromByteArray(byte[] cert) throws CertificateParsingException {
    return getCertfromByteArray(cert, BouncyCastleProvider.PROVIDER_NAME);
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Generate a selfsigned certificate.//from   w  ww .j ava 2s. co  m
 * 
 * @param dn subject and issuer DN
 * @param validity in days
 * @param policyId policy string ('2.5.29.32.0') or null
 * @param privKey private key
 * @param pubKey public key
 * @param sigAlg signature algorithm, you can use one of the contants AlgorithmConstants.SIGALG_XXX
 * @param isCA boolean true or false
 * 
 * @return X509Certificate, self signed
 * 
 * @throws IOException 
 * @throws CertificateException 
 * @throws OperatorCreationException 
 */
public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey,
        PublicKey pubKey, String sigAlg, boolean isCA)
        throws OperatorCreationException, CertificateException, IOException {
    return genSelfCert(dn, validity, policyId, privKey, pubKey, sigAlg, isCA,
            BouncyCastleProvider.PROVIDER_NAME);
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Generates a PKCS10CertificationRequest
 * // www.  j  ava 2 s . co m
 * Code Example:
 * -------------
 * An example of putting AltName and a password challenge in an 'attributes' set (taken from RequestMessageTest.test01Pkcs10RequestMessage() ):
 *       
 *      {@code
 *      // Create a P10 with extensions, in this case altNames with a DNS name
 *      ASN1EncodableVector altnameattr = new ASN1EncodableVector();
 *      altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
 *      // AltNames
 *      GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo1.bar.com");
 *      ExtensionsGenerator extgen = new ExtensionsGenerator();
 *      extgen.addExtension(Extension.subjectAlternativeName, false, san );
 *      Extensions exts = extgen.generate();
 *      altnameattr.add(new DERSet(exts));
 *    
 *      // Add a challenge password as well
 *      ASN1EncodableVector pwdattr = new ASN1EncodableVector();
 *      pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); 
 *      ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
 *      pwdvalues.add(new DERUTF8String("foo123"));
 *      pwdattr.add(new DERSet(pwdvalues));
 *    
 *      // Complete the Attribute section of the request, the set (Attributes)
 *      // contains one sequence (Attribute)
 *      ASN1EncodableVector v = new ASN1EncodableVector();
 *      v.add(new DERSequence(altnameattr));
 *      v.add(new DERSequence(pwdattr));
 *      DERSet attributes = new DERSet(v);
 *      }
 * 
 * @param signatureAlgorithm
 * @param subject   The request's subjectDN
 * @param publickey the public key for the certificate requesting signing
 * @param attributes    A set of attributes, for example, extensions, challenge password, etc.
 * @param privateKey the private key used to generate the certificate
 * @param provider
 * @return a PKCS10CertificateRequest based on the input parameters.
 * 
 * @throws OperatorCreationException if an error occurred while creating the signing key
 */
public static PKCS10CertificationRequest genPKCS10CertificationRequest(String signatureAlgorithm,
        X500Name subject, PublicKey publickey, ASN1Set attributes, PrivateKey privateKey, String provider)
        throws OperatorCreationException {

    ContentSigner signer;
    CertificationRequestInfo reqInfo;
    try {
        ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(publickey.getEncoded());
        SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(seq);
        reqInfo = new CertificationRequestInfo(subject, pkinfo, attributes);

        if (provider == null) {
            provider = BouncyCastleProvider.PROVIDER_NAME;
        }
        signer = new BufferingContentSigner(
                new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider).build(privateKey), 20480);
        signer.getOutputStream().write(reqInfo.getEncoded(ASN1Encoding.DER));
        signer.getOutputStream().flush();
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException was caught.", e);
    }
    byte[] sig = signer.getSignature();
    DERBitString sigBits = new DERBitString(sig);

    CertificationRequest req = new CertificationRequest(reqInfo, signer.getAlgorithmIdentifier(), sigBits);
    return new PKCS10CertificationRequest(req);
}

From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java

License:Open Source License

/**
 * Sends an OCSP request, gets a response and verifies the response as much as possible before returning it to the caller.
 * /*from   w  ww  .  ja  v  a2s . c o m*/
 * @return The OCSP response, or null of no correct response could be obtained.
 */
private SingleResp getOCSPResponse(final String ocspurl, final OCSPReq ocspRequest, final Certificate cert,
        final byte[] nonce, int expectedOcspRespCode, int expectedHttpRespCode) {
    if (log.isDebugEnabled()) {
        log.debug("Sending OCSP request to " + ocspurl + " regarding certificate with SubjectDN: "
                + CertTools.getSubjectDN(cert) + " - IssuerDN: " + CertTools.getIssuerDN(cert));
    }

    //----------------------- Open connection and send the request --------------//
    OCSPResp response = null;
    HttpURLConnection con = null;
    try {
        final URL url = new URL(ocspurl);
        con = (HttpURLConnection) url.openConnection();
        // we are going to do a POST
        con.setDoOutput(true);
        con.setRequestMethod("POST");

        // POST it
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        OutputStream os = con.getOutputStream();
        os.write(ocspRequest.getEncoded());
        os.close();

        final int httpRespCode = ((HttpURLConnection) con).getResponseCode();
        if (httpRespCode != expectedHttpRespCode) {
            log.info("HTTP response from OCSP request was " + httpRespCode + ". Expected "
                    + expectedHttpRespCode);
            handleContentOfErrorStream(con.getErrorStream());
            return null; // if it is an http error code we don't need to test any more
        }

        InputStream is = con.getInputStream();
        response = new OCSPResp(IOUtils.toByteArray(is));
        is.close();

    } catch (IOException e) {
        log.info("Unable to get an OCSP response. " + e.getLocalizedMessage());
        if (con != null) {
            handleContentOfErrorStream(con.getErrorStream());
        }
        return null;
    }

    // ------------ Verify the response signature --------------//
    BasicOCSPResp brep = null;
    try {
        brep = (BasicOCSPResp) response.getResponseObject();

        if ((expectedOcspRespCode != OCSPRespBuilder.SUCCESSFUL) && (brep != null)) {
            log.warn("According to RFC 2560, responseBytes are not set on error, but we got some.");
            return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses
        }

        if (brep == null) {
            log.warn("Cannot extract OCSP response object. OCSP response status: " + response.getStatus());
            return null;
        }

        X509CertificateHolder[] chain = brep.getCerts();
        boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(chain[0]));
        if (!verify) {
            log.warn("OCSP response signature was not valid");
            return null;
        }
    } catch (OCSPException | OperatorCreationException | CertificateException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to obtain or verify OCSP response. " + e.getLocalizedMessage());
        }
        return null;
    }

    // ------------- Verify the nonce ---------------//
    byte[] noncerep;
    try {
        noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue().getEncoded();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to read extension from OCSP response. " + e.getLocalizedMessage());
        }
        return null;
    }
    if (noncerep == null) {
        log.warn("Sent an OCSP request containing a nonce, but the OCSP response does not contain a nonce");
        return null;
    }

    try {
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        if (!Arrays.equals(nonce, oct.getOctets())) {
            log.warn("The nonce in the OCSP request and the OCSP response do not match");
            return null;
        }
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to read extension from OCSP response. " + e.getLocalizedMessage());
        }
        return null;
    }

    // ------------ Extract the single response and verify that it concerns a cert with the right serialnumber ----//
    SingleResp[] singleResps = brep.getResponses();
    if ((singleResps == null) || (singleResps.length == 0)) {
        if (log.isDebugEnabled()) {
            log.debug("The OCSP response object contained no responses.");
        }
        return null;
    }

    SingleResp singleResponse = singleResps[0];
    CertificateID certId = singleResponse.getCertID();
    if (!certId.getSerialNumber().equals(CertTools.getSerialNumber(cert))) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "Certificate serialnumber in response does not match certificate serialnumber in request.");
        }
        return null;
    }

    // ------------ Return the single response ---------------//
    return singleResponse;
}

From source file:org.cesecore.util.provider.EkuPKIXCertPathCheckerTest.java

License:Open Source License

/** @return true if the extendedKeyUsage was accepted */
private boolean validateCert(KeyPair keyPair, boolean isCa, List<String> actualOids, List<String> requiredOids)
        throws Exception {
    final long now = System.currentTimeMillis();
    final List<Extension> additionalExtensions = new ArrayList<Extension>();
    if (actualOids != null) {
        List<KeyPurposeId> actual = new ArrayList<KeyPurposeId>();
        for (final String oid : actualOids) {
            actual.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(oid)));
        }/*w  ww.j av a  2s.c o  m*/
        final ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(actual.toArray(new KeyPurposeId[0]));
        final ASN1Sequence seq = ASN1Sequence.getInstance(extendedKeyUsage.toASN1Primitive());
        final Extension extension = new Extension(Extension.extendedKeyUsage, true, seq.getEncoded());
        additionalExtensions.add(extension);
    }
    final int ku;
    if (isCa) {
        ku = X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign;
    } else {
        ku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment;
    }
    final X509Certificate cert = CertTools.genSelfCertForPurpose("CN=dummy", new Date(now - 3600000L),
            new Date(now + 3600000L), null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, isCa, ku, null, null, BouncyCastleProvider.PROVIDER_NAME,
            true, additionalExtensions);
    final PKIXCertPathChecker pkixCertPathChecker = new EkuPKIXCertPathChecker(requiredOids);
    final Collection<String> unresolvedCritExts = new ArrayList<String>(
            Arrays.asList(new String[] { Extension.extendedKeyUsage.getId() }));
    pkixCertPathChecker.check(cert, unresolvedCritExts);
    return !unresolvedCritExts.contains(Extension.extendedKeyUsage.getId());
}

From source file:org.codice.ddf.security.certificate.generator.CertificateAuthority.java

License:Open Source License

JcaX509CertificateConverter newCertConverter() {
    return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
}

From source file:org.codice.ddf.security.certificate.generator.CertificateAuthority.java

License:Open Source License

ContentSigner getContentSigner() {
    try {//  ww w  .j  av a  2 s . c  o m
        return new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .build(getPrivateKey());
    } catch (Exception e) {
        throw new CertificateGeneratorException("Cannot create content signer of certificate authority", e);
    }
}

From source file:org.codice.ddf.security.certificate.generator.PkiTools.java

License:Open Source License

/**
 * Generate new RSA public/private key pair with 2048 bit key
 *
 * @return new generated key pair/*from  w  w w .  j  a va2  s. com*/
 * @throws CertificateGeneratorException
 */
public static KeyPair generateRsaKeyPair() {
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM, BouncyCastleProvider.PROVIDER_NAME);
        keyGen.initialize(RSA_KEY_LENGTH);
        return keyGen.generateKeyPair();
    } catch (Exception e) {
        throw new CertificateGeneratorException("Failed to generate new public/private key pair.", e);
    }
}