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.codice.ddf.security.certificate.generator.PkiTools.java

License:Open Source License

static KeyFactory getRsaKeyFactory() throws GeneralSecurityException {
    return KeyFactory.getInstance(ALGORITHM, BouncyCastleProvider.PROVIDER_NAME);
}

From source file:org.cryptomator.crypto.aes256.Aes256CryptorTest.java

License:Open Source License

@Test
public void foo() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        NoSuchProviderException {
    Security.addProvider(new BouncyCastleProvider());

    final byte[] iv = new byte[16];
    final byte[] keyBytes = new byte[16];
    final SecretKey key = new SecretKeySpec(keyBytes, "AES");
    final Cipher pkcs5PaddedCipher = Cipher.getInstance("AES/CTR/PKCS5Padding",
            BouncyCastleProvider.PROVIDER_NAME);
    pkcs5PaddedCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
    final Cipher unpaddedCipher = Cipher.getInstance("AES/CTR/NoPadding");
    unpaddedCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));

    // test data:
    final byte[] plaintextData = "Hello World".getBytes();
    final byte[] pkcs5PaddedCiphertext = pkcs5PaddedCipher.doFinal(plaintextData);
    final byte[] unpaddedCiphertext = unpaddedCipher.doFinal(plaintextData);

    Assert.assertFalse(Arrays.equals(pkcs5PaddedCiphertext, unpaddedCiphertext));
}

From source file:org.ejbca.batchenrollmentgui.BatchEnrollmentGUIView.java

License:Open Source License

@SuppressWarnings("unchecked")
private static CMSValidationResult validateCMS(final CMSSignedData signedData,
        final Collection<Certificate> trustedCerts) {

    final CMSValidationResult result = new CMSValidationResult();

    try {/*from  www. j  a v a2 s. c  o  m*/
        final ContentInfo ci = signedData.toASN1Structure();
        if (LOG.isDebugEnabled()) {
            LOG.debug("ci.content: " + ci.getContent() + "\n" + "signedContent: "
                    + signedData.getSignedContent());
        }

        final Object content = signedData.getSignedContent().getContent();

        if (content instanceof byte[]) {
            result.setContent((byte[]) content);
        }

        Store certs = signedData.getCertificates();
        SignerInformationStore signers = signedData.getSignerInfos();
        for (Object o : signers.getSigners()) {
            if (o instanceof SignerInformation) {
                SignerInformation si = (SignerInformation) o;

                if (LOG.isDebugEnabled()) {
                    LOG.debug("*** SIGNATURE: " + "\n" + si.getSID());
                }

                final Collection<X509CertificateHolder> signerCerts = (Collection<X509CertificateHolder>) certs
                        .getMatches(si.getSID());

                if (LOG.isDebugEnabled()) {
                    LOG.debug("signerCerts: " + signerCerts);
                }
                JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
                for (X509CertificateHolder signerCert : signerCerts) {
                    final X509Certificate signerX509Cert = jcaX509CertificateConverter
                            .getCertificate(signerCert);

                    // Verify the signature
                    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
                    JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
                            calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
                    boolean consistent = si
                            .verify(jcaSignerInfoVerifierBuilder.build(signerX509Cert.getPublicKey()));
                    if (consistent) {

                        if (LOG.isDebugEnabled()) {
                            LOG.debug((consistent ? "Consistent" : "Inconsistent") + " signature from "
                                    + signerX509Cert.getSubjectDN() + " issued by "
                                    + signerX509Cert.getIssuerDN());
                        }

                        result.setValidSignature(consistent);

                        try {
                            final List<X509Certificate> signerChain = validateChain(signerX509Cert, certs,
                                    trustedCerts);

                            result.setValidChain(true);
                            result.setSignerChain(signerChain);

                            JOptionPane.showMessageDialog(null,
                                    "Found valid signature from \"" + signerX509Cert.getSubjectDN() + "\"",
                                    "Signature check", JOptionPane.INFORMATION_MESSAGE);

                        } catch (CertPathBuilderException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, "Error: Certificate path:\n" + ex.getMessage(),
                                    "Signature check", JOptionPane.ERROR_MESSAGE);
                        } catch (CertPathValidatorException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null,
                                    "Error: Certificate validation:\n" + ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (InvalidAlgorithmParameterException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (NoSuchAlgorithmException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (GeneralSecurityException e) {
                            //Crappy catch-all, but not much to do due to underlying BC-code
                            result.setError(e.getMessage());
                            JOptionPane.showMessageDialog(null, e.getMessage(),
                                    "Error: Certificate validation:\n", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        result.setError("Inconsistent signature!");
                        JOptionPane.showMessageDialog(null, "Error: Inconsisten signature!", "Signature check",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }

            }
        }

    } catch (CMSException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    } catch (OperatorCreationException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    } catch (CertificateException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    }
    return result;
}

From source file:org.ejbca.batchenrollmentgui.ConnectDialog.java

License:Open Source License

private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//NOPMD//GEN-FIRST:event_connectButtonActionPerformed
    settings = new ConnectSettings();
    settings.setUrl(urlTextField.getText());
    settings.setTruststoreType((String) truststoreTypeComboBox.getSelectedItem());
    settings.setTruststoreFile(truststoreFilePathTextField.getText());
    settings.setTruststorePassword(truststorePasswordField.getPassword());
    settings.setKeystoreType((String) keystoreTypeComboBox.getSelectedItem());
    settings.setKeystoreFile(keystoreFilePathTextField.getText());
    //        settings.setKeystorePassword(keystorePasswordField.getPassword());

    try {//from   w  ww.  j  a  v  a2  s.c  o  m
        Properties properties = new Properties();
        properties.put("url", settings.getUrl());
        properties.put("truststoreType", settings.getTruststoreType());
        properties.put("truststoreFile", settings.getTruststoreFile());
        properties.put("truststorePassword", new String(settings.getTruststorePassword()));
        properties.put("keystoreType", settings.getKeystoreType());
        properties.put("keystoreFile", settings.getKeystoreFile());
        properties.store(new FileOutputStream(CONNECT_FILE), "Connect settings");
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "Could not save configuration:\n" + ex.getMessage(), "Connect",
                JOptionPane.WARNING_MESSAGE);
    }

    try {

        final String urlstr = settings.getUrl() + WS_PATH;

        KeyStore.CallbackHandlerProtection pp = new KeyStore.CallbackHandlerProtection(new CallbackHandler() {

            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    if (callbacks[i] instanceof PasswordCallback) {
                        final PasswordCallback pc = (PasswordCallback) callbacks[i];

                        passwordLabel.setText(pc.getPrompt());
                        passwordField.setText("");

                        JOptionPane.showMessageDialog(ConnectDialog.this, passwordPanel, "Connect",
                                JOptionPane.PLAIN_MESSAGE);
                        if (passwordField.getPassword() != null) {
                            pc.setPassword(passwordField.getPassword());
                        }
                    } else {
                        throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
                    }
                }
            }
        });

        final KeyStore keystore;
        final KeyManagerFactory kKeyManagerFactory = KeyManagerFactory.getInstance("SunX509");

        if (settings.getKeystoreType().contains("Windows")) {
            // CSP
            keystore = getLoadedKeystoreCSP(settings.getKeystoreType(), pp);
            kKeyManagerFactory.init(keystore, null);
        } else if (settings.getKeystoreType().equals("PKCS11")) {
            // PKCS11
            keystore = getLoadedKeystorePKCS11("PKCS11", settings.getKeystoreFile(),
                    settings.getKeystorePassword(), pp);
            kKeyManagerFactory.init(keystore, null);
        } else {
            // PKCS12 must use BC as provider but not JKS
            final String provider;
            if (settings.getKeystoreType().equals("PKCS12")) {
                provider = BouncyCastleProvider.PROVIDER_NAME;
            } else {
                provider = null;
            }

            // Ask for password
            char[] authcode;
            passwordLabel.setText("Enter password for keystore:");
            passwordField.setText("");
            JOptionPane.showMessageDialog(ConnectDialog.this, passwordPanel, "Connect",
                    JOptionPane.PLAIN_MESSAGE);
            if (passwordField.getPassword() != null) {
                authcode = passwordField.getPassword();
            } else {
                authcode = null;
            }

            // Other keystores for instance JKS
            keystore = getLoadedKeystore(settings.getKeystoreFile(), authcode, settings.getKeystoreType(),
                    provider);

            // JKS has password on keys and need to be inited with password
            if (settings.getKeystoreType().equals("JKS")) {
                kKeyManagerFactory.init(keystore, authcode);
            } else {
                kKeyManagerFactory.init(keystore, null);
            }
        }

        final KeyStore keystoreTrusted;
        if (TRUSTSTORE_TYPE_PEM.equals(settings.getTruststoreType())) {
            keystoreTrusted = KeyStore.getInstance("JKS");
            keystoreTrusted.load(null, null);
            final Collection<Certificate> certs = CertTools
                    .getCertsFromPEM(new FileInputStream(settings.getTruststoreFile()), Certificate.class);
            int i = 0;
            for (Object o : certs) {
                if (o instanceof Certificate) {
                    keystoreTrusted.setCertificateEntry("cert-" + i, (Certificate) o);
                    i++;
                }
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Loaded " + i + " certs to truststore");
            }
        } else if (TRUSTSTORE_TYPE_KEYSTORE.equals(settings.getTruststoreType())) {
            keystoreTrusted = KeyStore.getInstance("JKS");
            keystoreTrusted.load(null, null);
            final Enumeration<String> aliases = keystore.aliases();
            int i = 0;
            while (aliases.hasMoreElements()) {
                final String alias = aliases.nextElement();
                if (keystore.isCertificateEntry(alias)) {
                    keystoreTrusted.setCertificateEntry(alias, keystore.getCertificate(alias));
                    i++;
                }
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Loaded " + i + " certs to truststore");
            }
        } else {
            keystoreTrusted = KeyStore.getInstance(settings.getTruststoreType());
            keystoreTrusted.load(new FileInputStream(settings.getTruststoreFile()),
                    settings.getTruststorePassword());
        }

        final TrustManagerFactory tTrustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        tTrustManagerFactory.init(keystoreTrusted);

        KeyManager[] keyManagers = kKeyManagerFactory.getKeyManagers();

        //        final SSLSocketFactory factory = sslc.getSocketFactory();
        for (int i = 0; i < keyManagers.length; i++) {
            if (keyManagers[i] instanceof X509KeyManager) {
                keyManagers[i] = new GUIKeyManager((X509KeyManager) keyManagers[i]);
            }
        }

        // Now construct a SSLContext using these (possibly wrapped)
        // KeyManagers, and the TrustManagers. We still use a null
        // SecureRandom, indicating that the defaults should be used.
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagers, tTrustManagerFactory.getTrustManagers(), new SecureRandom());

        // Finally, we get a SocketFactory, and pass it to SimpleSSLClient.
        SSLSocketFactory factory = context.getSocketFactory();

        HttpsURLConnection.setDefaultSSLSocketFactory(factory);

        QName qname = new QName("http://ws.protocol.core.ejbca.org/", "EjbcaWSService");
        EjbcaWSService service = new EjbcaWSService(new URL(urlstr), qname);
        ejbcaWS = service.getEjbcaWSPort();
        dispose();
    } catch (Exception ex) {
        LOG.error("Connection failed", ex);
        JOptionPane.showMessageDialog(this, ex.getMessage(), "Connect", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java

License:Open Source License

private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey,
        PublicKey pubKey, String sigAlg, boolean isCA)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, OperatorCreationException, CertificateException, IOException {
    int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
    // Create self signed certificate
    Date firstDate = new Date();
    // Set starting date to tomorrow
    firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000));
    Date lastDate = new Date();
    // Set Expiry in two days
    lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from  w ww .j  ava2  s. c  o m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            publicKey = pubKey;
        } catch (NullPointerException e) {
            publicKey = pubKey;
        }
    } else {
        publicKey = pubKey;
    }
    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
            (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn),
            new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn),
            pkinfo);
    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }
    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            ASN1InputStream spkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream apkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) spkiAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) apkiAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                spkiAsn1InputStream.close();
                apkiAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }
    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

From source file:org.ejbca.core.ejb.ra.EndEntityManagementSessionTest.java

License:Open Source License

/** Test revocation of an end entity. */
@Test//from   w  ww  .  jav  a  2 s .  co  m
public void testRevokeEndEntity() throws Exception {
    final String TEST_NAME = Thread.currentThread().getStackTrace()[1].getMethodName();
    final String USERNAME = TEST_NAME + "A";
    endEntityManagementSession.addUser(admin, USERNAME, pwd, "C=SE, O=PrimeKey, CN=" + USERNAME, null, null,
            true, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER,
            EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.TOKEN_SOFT_P12, 0, caid);
    usernames.add(USERNAME);
    final long now = System.currentTimeMillis();
    final Date date10sAgo = new Date(now - 10000L);
    final Date date2sAgo = new Date(now - 2000L);
    final Date date1hFromNow = new Date(now + 3600000L);
    final KeyPair keyPair = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    // Generate self signed certificates
    // This is really a bit strange with no "real" certificates. We can however revoke them anyhow even though they don't belong to a CA in the system
    // This may be useful in order to be able to create "dummy" certificates for specific compromised cases where you want to answer specifically for strange things.
    final X509Certificate x509Certificate1 = CertTools.genSelfCertForPurpose("CN=" + USERNAME, date10sAgo,
            date1hFromNow, null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA, false, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign,
            null, null, BouncyCastleProvider.PROVIDER_NAME, true, null);
    final String fingerprint1 = CertTools.getFingerprintAsString(x509Certificate1);
    final X509Certificate x509Certificate2 = CertTools.genSelfCertForPurpose("CN=" + USERNAME, date10sAgo,
            date2sAgo, null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA, false, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign,
            null, null, BouncyCastleProvider.PROVIDER_NAME, true, null);
    final String fingerprint2 = CertTools.getFingerprintAsString(x509Certificate2);
    final X509Certificate x509Certificate3 = CertTools.genSelfCertForPurpose("CN=" + USERNAME, date10sAgo,
            date1hFromNow, null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA, false, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign,
            null, null, BouncyCastleProvider.PROVIDER_NAME, true, null);
    final String fingerprint3 = CertTools.getFingerprintAsString(x509Certificate3);
    final X509Certificate x509Certificate4 = CertTools.genSelfCertForPurpose("CN=" + USERNAME, date10sAgo,
            date1hFromNow, null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA, false, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign,
            null, null, BouncyCastleProvider.PROVIDER_NAME, true, null);
    final String fingerprint4 = CertTools.getFingerprintAsString(x509Certificate4);
    final X509Certificate x509Certificate5 = CertTools.genSelfCertForPurpose("CN=" + USERNAME, date10sAgo,
            date2sAgo, null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA, false, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign,
            null, null, BouncyCastleProvider.PROVIDER_NAME, true, null);
    final String fingerprint5 = CertTools.getFingerprintAsString(x509Certificate5);
    final X509Certificate x509Certificate6 = CertTools.genSelfCertForPurpose("CN=" + USERNAME, date10sAgo,
            date1hFromNow, null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA, false, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign,
            null, null, BouncyCastleProvider.PROVIDER_NAME, true, null);
    final String fingerprint6 = CertTools.getFingerprintAsString(x509Certificate6);
    try {
        // Persists self signed certificates
        internalCertStoreSession.storeCertificateNoAuth(admin, x509Certificate1, USERNAME, fingerprint1,
                CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY,
                CertificateProfileConstants.CERTPROFILE_NO_PROFILE, EndEntityInformation.NO_ENDENTITYPROFILE,
                null, now);
        internalCertStoreSession.storeCertificateNoAuth(admin, x509Certificate2, USERNAME, fingerprint2,
                CertificateConstants.CERT_ARCHIVED, CertificateConstants.CERTTYPE_ENDENTITY,
                CertificateProfileConstants.CERTPROFILE_NO_PROFILE, EndEntityInformation.NO_ENDENTITYPROFILE,
                null, now);
        internalCertStoreSession.storeCertificateNoAuth(admin, x509Certificate3, USERNAME, fingerprint3,
                CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION, CertificateConstants.CERTTYPE_ENDENTITY,
                CertificateProfileConstants.CERTPROFILE_NO_PROFILE, EndEntityInformation.NO_ENDENTITYPROFILE,
                null, now);
        internalCertStoreSession.storeCertificateNoAuth(admin, x509Certificate4, USERNAME, fingerprint4,
                CertificateConstants.CERT_REVOKED, CertificateConstants.CERTTYPE_ENDENTITY,
                CertificateProfileConstants.CERTPROFILE_NO_PROFILE, EndEntityInformation.NO_ENDENTITYPROFILE,
                null, now);
        // A certificate that has expired, but status has not been changed to ARCHIVED by the CRL worker
        internalCertStoreSession.storeCertificateNoAuth(admin, x509Certificate5, USERNAME, fingerprint5,
                CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY,
                CertificateProfileConstants.CERTPROFILE_NO_PROFILE, EndEntityInformation.NO_ENDENTITYPROFILE,
                null, now);
        // Artificial test vector where certificate has not expired, but the status is still set to archived
        internalCertStoreSession.storeCertificateNoAuth(admin, x509Certificate6, USERNAME, fingerprint5,
                CertificateConstants.CERT_ARCHIVED, CertificateConstants.CERTTYPE_ENDENTITY,
                CertificateProfileConstants.CERTPROFILE_NO_PROFILE, EndEntityInformation.NO_ENDENTITYPROFILE,
                null, now);
        // Revoke user
        endEntityManagementSession.revokeUser(admin, USERNAME, RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED);
        // Get all certificate except the revoked ones
        final List<CertificateDataWrapper> cdws = certificateStoreSession.getCertificateDataByUsername(USERNAME,
                false, Arrays.asList(CertificateConstants.CERT_REVOKED));
        assertEquals("Expected that revokeUser call would not touch ARCHIVED or expired certificates.", 3,
                cdws.size());
        final List<String> remainingFingerprints = Arrays.asList(
                cdws.get(0).getCertificateData().getFingerprint(),
                cdws.get(1).getCertificateData().getFingerprint(),
                cdws.get(2).getCertificateData().getFingerprint());
        assertTrue("Expected archived and expired certificate to not be revoked.",
                remainingFingerprints.contains(fingerprint2));
        assertTrue("Expected active and expired certificate to not be revoked.",
                remainingFingerprints.contains(fingerprint5));
        assertTrue("Expected archived and non-expired certificate to not be revoked.",
                remainingFingerprints.contains(fingerprint6));
    } finally {
        // Clean up
        final List<CertificateDataWrapper> cdws = certificateStoreSession.getCertificateDataByUsername(USERNAME,
                false, null);
        for (final CertificateDataWrapper cdw : cdws) {
            internalCertStoreSession.removeCertificate(cdw.getCertificateData().getFingerprint());
        }
    }
}

From source file:org.ejbca.core.ejb.StartupSingletonBean.java

License:Open Source License

@PostConstruct
private void startup() {
    ////from  w  ww.ja va  2s  .c  om
    // Run all "safe" initializations first, 
    // i.e. those that does not depend on other running beans, components etc

    // Log a startup message
    String iMsg = InternalEjbcaResources.getInstance().getLocalizedMessage("startservice.startup",
            GlobalConfiguration.EJBCA_VERSION);
    log.info(iMsg);

    // Reinstall BC-provider to help re-deploys to work
    log.trace(">init re-installing BC-provider");
    CryptoProviderTools.removeBCProvider();
    CryptoProviderTools.installBCProvider();

    // Run java seed collector, that can take a little time the first time it is run
    log.trace(">init initializing random seed");
    SecureRandom rand = new SecureRandom();
    rand.nextInt();

    //
    // Start services that requires calling other beans or components
    //

    // We really need BC to be installed. This is an attempt to fix a bug where the ServiceSessionBean
    // crashes from not finding the BC-provider.
    int waitTime = 0;
    while (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null && waitTime++ < 5) {
        log.info("Waiting for BC provider to be installed..");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("Waiting for BC provider failed.", e);
            break;
        }
    }

    // We have to read CAs into cache (and upgrade them) early, because the log system may use CAs for signing logs

    log.trace(">init CryptoTokenFactory just to load those classes that are available");
    CryptoTokenFactory.instance();

    // Load CAs at startup to improve impression of speed the first time a CA is accessed, it takes a little time to load it.
    log.trace(">init loading CAs into cache");
    try {
        caAdminSession.initializeAndUpgradeCAs();
    } catch (Exception e) {
        log.error("Error creating CAAdminSession: ", e);
    }

    // Make a log row that EJBCA is starting
    Map<String, Object> details = new LinkedHashMap<>();
    details.put("msg", iMsg);
    logSession.log(EjbcaEventTypes.EJBCA_STARTING, EventStatus.SUCCESS, EjbcaModuleTypes.SERVICE,
            EjbcaServiceTypes.EJBCA, authenticationToken.toString(), null, getHostName(), null, details);

    // Log the type of security audit configuration that we have enabled.
    log.trace(">init security audit device configuration");
    final Set<String> loggerIds = AuditDevicesConfig.getAllDeviceIds();
    if (loggerIds.isEmpty()) {
        final String msg = InternalEjbcaResources.getInstance()
                .getLocalizedMessage("startservices.noauditdevices");
        log.info(msg);
    } else {
        if (!checkForProtectedAudit(authenticationToken, loggerIds)) {
            // Make a log row that no integrity protected device is configured
            final String msg = InternalEjbcaResources.getInstance()
                    .getLocalizedMessage("startservices.noprotectedauditdevices");
            final Map<String, Object> logdetails = new LinkedHashMap<>();
            logdetails.put("msg", msg);
            logSession.log(EventTypes.LOG_MANAGEMENT_CHANGE, EventStatus.VOID, ModuleTypes.SECURITY_AUDIT,
                    ServiceTypes.CORE, authenticationToken.toString(), null, null, null, logdetails);
        }
    }

    // Initialize authorization system, if not done already
    log.trace(">init ComplexAccessControlSession to check for initial root role");
    final boolean isFreshInstallation = complexAccessControlSession.initializeAuthorizationModule();

    log.trace(">init calling ServiceSession.load");
    try {
        serviceSession.load();
    } catch (Exception e) {
        log.error("Error init ServiceSession: ", e);
    }

    // Load Certificate profiles at startup to upgrade them if needed
    log.trace(">init loading CertificateProfile to check for upgrades");
    try {
        certificateProfileSession.initializeAndUpgradeProfiles();
    } catch (Exception e) {
        log.error("Error initializing certificate profiles: ", e);
    }

    // Load EndEntity profiles at startup to upgrade them if needed
    // And add this node to list of nodes
    log.trace(">init loading EndEntityProfile to check for upgrades");
    try {
        endEntityProfileSession.initializeAndUpgradeProfiles();
    } catch (Exception e) {
        log.error("Error initializing end entity profiles: ", e);
    }

    // Add this node's hostname to list of nodes
    log.trace(">init checking if this node is in the list of nodes");
    try {
        // Requires a transaction in order to create the initial global configuration
        tx.begin();
        try {
            final GlobalConfiguration config = (GlobalConfiguration) globalConfigurationSession
                    .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
            final Set<String> nodes = config.getNodesInCluster();
            final String hostname = getHostName();
            if (hostname != null && !nodes.contains(hostname)) {
                log.debug("Adding this node (" + hostname + ") to the list of nodes");
                nodes.add(hostname);
                config.setNodesInCluster(nodes);
                globalConfigurationSession.saveConfiguration(authenticationToken, config);
            }
        } finally {
            tx.commit();
        }
    } catch (Exception e) {
        log.error("Error adding host to node list in global configuration: ", e);
    }

    log.trace(">init SignSession to check for unique issuerDN,serialNumber index");
    // Call the check for unique index, since first invocation will perform the database
    // operation and avoid a performance hit for the first request where this is checked.
    certCreateSession.isUniqueCertificateSerialNumberIndex();

    /*
     * FIXME: This is a hack, because we need some sort of annotation or service loader to make sure 
     * that the AccessMatchValue-implementing enums get initialized at runtime. Sadly, enums aren't 
     * initialized until they're called, which causes trouble with this registry. 
     * 
     * These lines are to be removed once a dynamic initialization heuristic has been developed.
     * 
     */
    try {
        Class.forName(X500PrincipalAccessMatchValue.class.getName());
        Class.forName(CliUserAccessMatchValue.class.getName());
        Class.forName(PublicAccessMatchValue.class.getName());
    } catch (ClassNotFoundException e) {
        log.error("Failure during match value initialization", e);
    }
    // Perform (automatic) upgrades, if needed
    upgradeSession.performPreUpgrade(isFreshInstallation);
    upgradeSession.performUpgrade();
    // Start key reload timer
    ocspResponseGeneratorSession.initTimers();
    // Start CA certificate cache reload
    certificateStoreSession.initTimers();
    // Start legacy background service for renewal of OCSP signers via EJBCA WS calls to CA
    ocspKeyRenewalSession.startTimer();
    // Verify that the EJB CLI user (if present) cannot be used to generate certificates
    final String cliUsername = EjbcaConfiguration.getCliDefaultUser();
    try {
        final EndEntityInformation defaultCliUser = endEntityAccessSession.findUser(authenticationToken,
                cliUsername);
        if (defaultCliUser != null && defaultCliUser.getStatus() == EndEntityConstants.STATUS_NEW) {
            try {
                endEntityManagementSession.setUserStatus(authenticationToken, cliUsername,
                        EndEntityConstants.STATUS_GENERATED);
            } catch (ApprovalException e) {
                log.warn("The EJBCA CLI user '" + cliUsername
                        + "' could be used for certificate enrollment. Please correct the status manually. Failed with: "
                        + e.getMessage());
            } catch (FinderException e) {
                log.warn("The EJBCA CLI user '" + cliUsername
                        + "' could be used for certificate enrollment. Please correct the status manually. Failed with: "
                        + e.getMessage());
            } catch (WaitingForApprovalException e) {
                log.warn("The EJBCA CLI user '" + cliUsername
                        + "' could be used for certificate enrollment. Please correct the status manually. Failed with: "
                        + e.getMessage());
            }
        }
    } catch (AuthorizationDeniedException e) {
        log.warn("Unable to check if the EJBCA CLI user '" + cliUsername
                + "' could be used for certificate enrollment. Please check and correct the status manually. Failed with: "
                + e.getMessage());
    }
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

License:Open Source License

@Override
public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken,
        final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException,
        IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException {
    if (log.isTraceEnabled()) {
        log.trace(">extendedService");
    }//w w  w.  ja v  a 2  s  . c  om
    if (!(request instanceof CmsCAServiceRequest)) {
        throw new IllegalExtendedCAServiceRequestException();
    }
    if (getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) {
        final String msg = intres.getLocalizedMessage("caservice.notactive", "CMS");
        log.error(msg);
        throw new ExtendedCAServiceNotActiveException(msg);
    }
    ExtendedCAServiceResponse returnval = null;
    final X509Certificate signerCert = (X509Certificate) certificatechain.get(0);
    final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest) request;
    // Create the signed data
    final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();
    try {
        byte[] resp = serviceReq.getDoc();
        // Add our signer info and sign the message
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) {
            final List<X509Certificate> x509CertChain = new ArrayList<X509Certificate>();
            for (Certificate certificate : certificatechain) {
                x509CertChain.add((X509Certificate) certificate);
            }
            gen1.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(x509CertChain)));
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            ASN1ObjectIdentifier oid = AlgorithmTools
                    .getSignAlgOidFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privKey.getAlgorithm());
            String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
            JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            ContentSigner contentSigner = signerBuilder.build(privKey);
            gen1.addSignerInfoGenerator(builder.build(contentSigner, signerCert));
            final CMSTypedData msg = new CMSProcessableByteArray(resp);
            final CMSSignedData s = gen1.generate(msg, true);
            resp = s.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) {
            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(getCMSCertificate())
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                    PKCSObjectIdentifiers.des_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
            CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(resp),
                    jceCMSContentEncryptorBuilder.build());
            resp = ed.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_DECRYPT) != 0) {
            final CMSEnvelopedData ed = new CMSEnvelopedData(resp);
            final RecipientInformationStore recipients = ed.getRecipientInfos();
            final X500Name issuer = X500Name
                    .getInstance(getCMSCertificate().getIssuerX500Principal().getEncoded());
            final KeyTransRecipientId id = new KeyTransRecipientId(issuer,
                    getCMSCertificate().getSerialNumber());
            final RecipientInformation recipient = recipients.get(id);
            if (recipient != null) {
                JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(this.privKey);
                // Provider for decrypting the symmetric key 
                rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
                rec.setProvider(cryptoToken.getSignProviderName());
                // We can use a different provider for decrypting the content, for example of we used a PKCS#11 provider above we could use the BC provider below
                resp = recipient.getContent(rec);
            }
        }
        returnval = new CmsCAServiceResponse(resp);
    } catch (CMSException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (IOException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (OperatorCreationException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (CertificateEncodingException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<extendedService");
    }
    return returnval;
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

License:Open Source License

protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN,
        Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret,
        String expectedSignAlg)/*from  w  w w  . j a  v a2  s  .c om*/
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    assertNotNull("No response from server.", retMsg);
    assertTrue("Response was of 0 length.", retMsg.length > 0);
    boolean pbe = (pbeSecret != null);
    //
    // Parse response message
    //
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    // The signer, i.e. the CA, check it's the right CA
    PKIHeader header = respObject.getHeader();

    // Check that the message is signed with the correct digest alg
    if (StringUtils.isEmpty(expectedSignAlg)) {
        expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId();
    }
    // if cacert is ECDSA we should expect an ECDSA signature alg
    //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) {
    //    expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) {
    //    expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) {
    //    expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId();
    //}
    if (signed) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals(expectedSignAlg, algId.getAlgorithm().getId());
    }
    if (pbe) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(),
                CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption
    }

    // Check that the signer is the expected CA    
    assertEquals(header.getSender().getTagNo(), 4);

    X500Name expissuer = new X500Name(issuerDN);
    X500Name actissuer = new X500Name(header.getSender().getName().toString());
    assertEquals(expissuer, actissuer);
    if (signed) {
        // Verify the signature
        byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString bs = respObject.getProtection();
        Signature sig;
        try {
            sig = Signature.getInstance(expectedSignAlg, "BC");
            sig.initVerify(cacert);
            sig.update(protBytes);
            boolean ret = sig.verify(bs.getBytes());
            assertTrue(ret);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (SignatureException e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }
    if (pbe) {
        ASN1OctetString os = header.getSenderKID();
        assertNotNull(os);
        String keyId = CmpMessageHelper.getStringFromOctets(os);
        log.debug("Found a sender keyId: " + keyId);
        // Verify the PasswordBased protection of the message
        byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString protection = respObject.getProtection();
        AlgorithmIdentifier pAlg = header.getProtectionAlg();
        log.debug("Protection type is: " + pAlg.getAlgorithm().getId());
        PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters());
        int iterationCount = pp.getIterationCount().getPositiveValue().intValue();
        log.debug("Iteration count is: " + iterationCount);
        AlgorithmIdentifier owfAlg = pp.getOwf();
        // Normal OWF alg is 1.3.14.3.2.26 - SHA1
        log.debug("Owf type is: " + owfAlg.getAlgorithm().getId());
        AlgorithmIdentifier macAlg = pp.getMac();
        // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1
        log.debug("Mac type is: " + macAlg.getAlgorithm().getId());
        byte[] salt = pp.getSalt().getOctets();
        // log.info("Salt is: "+new String(salt));
        byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0];
        byte[] basekey = new byte[raSecret.length + salt.length];
        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
        for (int i = 0; i < salt.length; i++) {
            basekey[raSecret.length + i] = salt[i];
        }
        // Construct the base key according to rfc4210, section 5.1.3.1
        MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(),
                BouncyCastleProvider.PROVIDER_NAME);
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7
        String macOid = macAlg.getAlgorithm().getId();
        Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME);
        SecretKey key = new SecretKeySpec(basekey, macOid);
        mac.init(key);
        mac.reset();
        mac.update(protectedBytes, 0, protectedBytes.length);
        byte[] out = mac.doFinal();
        // My out should now be the same as the protection bits
        byte[] pb = protection.getBytes();
        boolean ret = Arrays.equals(out, pb);
        assertTrue(ret);
    }

    // --SenderNonce
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    byte[] nonce = header.getSenderNonce().getOctets();
    assertEquals(nonce.length, 16);

    // --Recipient Nonce
    // recipient nonce should be the same as we sent away as sender nonce
    nonce = header.getRecipNonce().getOctets();
    assertEquals(new String(nonce), new String(senderNonce));

    // --Transaction ID
    // transid should be the same as the one we sent
    nonce = header.getTransactionID().getOctets();
    assertEquals(new String(nonce), new String(transId));

}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

License:Open Source License

/**
 * @param serialNr serial number of the certificate to verify
 * @param cacert issuer of the certificate to verify
 * @param useGet if true GET will be used instead of POST as HTTP method
 * @return response can contain and an error code but the fnr is allways null, never returns null.
 * @throws OCSPException /*from  w  w w .j av  a  2  s  .  c  om*/
 * @throws IOException
 * @throws OperatorCreationException if Signer couldn't be created
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws CertificateException 
 * @throws KeyManagementException 
 * @throws UnrecoverableKeyException 
 */
public OCSPUnidResponse lookup(BigInteger serialNr, X509Certificate cacert, boolean useGet)
        throws OCSPException, IOException, OperatorCreationException, UnrecoverableKeyException,
        KeyManagementException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
    if (this.httpReqPath == null) {
        // If we didn't pass a url to the constructor and the cert does not have the URL, we will fail...
        OCSPUnidResponse ret = new OCSPUnidResponse();
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_OCSP_URI);
        return ret;
    }
    final OCSPReqBuilder gen = new OCSPReqBuilder();
    final CertificateID certId = new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(),
            (X509Certificate) cacert, serialNr);
    gen.addRequest(certId);
    if (!useGet) {
        // Add a nonce to the request
        gen.setRequestExtensions(this.extensions);
    }
    final OCSPReq req;
    if (this.signKey != null) {
        final X509Certificate localCertChain[] = this.certChain != null ? this.certChain
                : new X509Certificate[] { (X509Certificate) cacert };
        final JcaX509CertificateHolder[] certificateHolderChain = CertTools
                .convertToX509CertificateHolder(localCertChain);
        gen.setRequestorName(certificateHolderChain[0].getSubject());
        req = gen.build(
                new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(this.signKey), 20480),
                certificateHolderChain);
    } else {
        req = gen.build();
    }
    // write request if directory exists.
    File ocspReqDir = new File(requestDirectory);
    if (ocspReqDir.isDirectory()) {
        OutputStream os = new FileOutputStream(new File(ocspReqDir, serialNr.toString()));
        os.write(req.getEncoded());
        os.close();
    }
    // Send the request and receive a BasicResponse
    return sendOCSPRequest(req.getEncoded(), cacert, useGet);
}