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.ejbca.ui.cli.ca.CaImportCRLCommand.java

License:Open Source License

@Override
public CommandResult execute(ParameterContainer parameters) {
    log.trace(">execute()");
    CryptoProviderTools.installBCProvider();

    try {//w  w w  .j  a v a  2  s.  c o  m
        // Parse arguments
        final String caname = parameters.get(CA_NAME_KEY);
        final String crl_file = parameters.get(CRL_FILE_KEY);
        final String operationsMode = parameters.get(OPERATION_KEY);
        final boolean strict = operationsMode.equalsIgnoreCase(STRICT_OP);
        final boolean adaptive = operationsMode.equalsIgnoreCase(ADAPTIVE_OP);
        if (!strict && !adaptive && !operationsMode.equalsIgnoreCase(LENIENT_OP)) {
            //None of the above.
            log.error("Operations mode must be one of " + STRICT_OP + ", " + LENIENT_OP + " or " + ADAPTIVE_OP
                    + ".");
            return CommandResult.CLI_FAILURE;
        }
        // Fetch CA and related info
        final CAInfo cainfo = getCAInfo(getAuthenticationToken(), caname);
        final X509Certificate cacert = (X509Certificate) cainfo.getCertificateChain().iterator().next();
        final String issuer = CertTools.stringToBCDNString(cacert.getSubjectDN().toString());
        log.info("CA: " + issuer);
        // Read the supplied CRL and verify that it is issued by the specified CA
        final X509CRL x509crl = (X509CRL) CertTools.getCertificateFactory()
                .generateCRL(new FileInputStream(crl_file));
        if (!x509crl.getIssuerX500Principal().equals(cacert.getSubjectX500Principal())) {
            throw new IOException("CRL wasn't issued by this CA");
        }
        x509crl.verify(cacert.getPublicKey());
        int crl_no = CrlExtensions.getCrlNumber(x509crl).intValue();
        log.info("Processing CRL #" + crl_no);
        int miss_count = 0; // Number of certs not already in database
        int revoked = 0; // Number of certs activly revoked by this algorithm
        int already_revoked = 0; // Number of certs already revoked in database and ignored in non-strict mode
        final String missing_user_name = MISSING_USERNAME_PREFIX + caname;
        @SuppressWarnings("unchecked")
        Set<X509CRLEntry> entries = (Set<X509CRLEntry>) x509crl.getRevokedCertificates();
        if (entries != null) {
            for (final X509CRLEntry entry : entries) {
                final BigInteger serialNr = entry.getSerialNumber();
                final String serialHex = serialNr.toString(16).toUpperCase();
                final String username = EjbRemoteHelper.INSTANCE
                        .getRemoteSession(CertificateStoreSessionRemote.class)
                        .findUsernameByCertSerno(serialNr, issuer);
                // If this certificate exists and has an assigned username, we keep using that. Otherwise we create this coupling to a user.
                if (username == null) {
                    log.info("Certificate '" + serialHex + "' missing in the database");
                    if (strict) {
                        throw new IOException(
                                "Aborted! Running in strict mode and is missing certificate in database.");
                    }
                    miss_count++;
                    if (!adaptive) {
                        continue;
                    }
                    final Date time = new Date(); // time from which certificate is valid
                    final KeyPair key_pair = KeyTools.genKeys("2048", AlgorithmConstants.KEYALGORITHM_RSA);

                    final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
                            (ASN1Sequence) ASN1Primitive.fromByteArray(key_pair.getPublic().getEncoded()));
                    final X500Name dnName = new X500Name(
                            "CN=Dummy Missing in Imported CRL, serialNumber=" + serialHex);
                    final Date notAfter = new Date(time.getTime() + 1000L * 60 * 60 * 24 * 365 * 10); // 10 years of life
                    final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
                            X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()), serialNr, time,
                            notAfter, dnName, pkinfo);
                    final ContentSigner signer = new BufferingContentSigner(
                            new JcaContentSignerBuilder("SHA1withRSA")
                                    .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                                    .build(key_pair.getPrivate()),
                            20480);
                    final X509CertificateHolder certHolder = certbuilder.build(signer);
                    final X509Certificate certificate = (X509Certificate) CertTools
                            .getCertfromByteArray(certHolder.getEncoded());

                    final String fingerprint = CertTools.getFingerprintAsString(certificate);
                    // We add all certificates that does not have a user already to "missing_user_name"
                    final EndEntityInformation missingUserEndEntityInformation = EjbRemoteHelper.INSTANCE
                            .getRemoteSession(EndEntityAccessSessionRemote.class)
                            .findUser(getAuthenticationToken(), missing_user_name);
                    if (missingUserEndEntityInformation == null) {
                        // Add the user and change status to REVOKED
                        log.debug("Loading/updating user " + missing_user_name);
                        final EndEntityInformation userdataNew = new EndEntityInformation(missing_user_name,
                                CertTools.getSubjectDN(certificate), cainfo.getCAId(), null, null,
                                EndEntityConstants.STATUS_NEW, new EndEntityType(EndEntityTypes.ENDUSER),
                                SecConst.EMPTY_ENDENTITYPROFILE,
                                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null,
                                SecConst.TOKEN_SOFT_BROWSERGEN, SecConst.NO_HARDTOKENISSUER, null);
                        userdataNew.setPassword("foo123");
                        EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class)
                                .addUser(getAuthenticationToken(), userdataNew, false);
                        log.info("User '" + missing_user_name + "' has been added.");
                        EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class)
                                .setUserStatus(getAuthenticationToken(), missing_user_name,
                                        EndEntityConstants.STATUS_REVOKED);
                        log.info("User '" + missing_user_name + "' has been updated.");
                    }
                    EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateStoreSessionRemote.class)
                            .storeCertificate(getAuthenticationToken(), certificate, missing_user_name,
                                    fingerprint, CertificateConstants.CERT_ACTIVE,
                                    CertificateConstants.CERTTYPE_ENDENTITY,
                                    CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null,
                                    new Date().getTime());
                    log.info("Dummy certificate  '" + serialHex + "' has been stored.");
                }
                // This check will not catch a certificate with status CertificateConstants.CERT_ARCHIVED
                if (!strict && EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateStoreSessionRemote.class)
                        .isRevoked(issuer, serialNr)) {
                    log.info("Certificate '" + serialHex + "' is already revoked");
                    already_revoked++;
                    continue;
                }
                log.info("Revoking '" + serialHex + "' " + "(" + serialNr.toString() + ")");
                try {
                    int reason = getCRLReasonValue(entry);
                    log.info("Reason code: " + reason);
                    EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class)
                            .revokeCert(getAuthenticationToken(), serialNr, entry.getRevocationDate(), issuer,
                                    reason, false);
                    revoked++;
                } catch (AlreadyRevokedException e) {
                    already_revoked++;
                    log.warn("Failed to revoke '" + serialHex
                            + "'. (Status might be 'Archived'.) Error message was: " + e.getMessage());
                }
            }
        } // if (entries != null)
        if (EjbRemoteHelper.INSTANCE.getRemoteSession(CrlStoreSessionRemote.class).getLastCRLNumber(issuer,
                false) < crl_no) {
            EjbRemoteHelper.INSTANCE.getRemoteSession(CrlStoreSessionRemote.class).storeCRL(
                    getAuthenticationToken(), x509crl.getEncoded(), CertTools.getFingerprintAsString(cacert),
                    crl_no, issuer, x509crl.getThisUpdate(), x509crl.getNextUpdate(), -1);
        } else {
            if (strict) {
                throw new IOException("CRL #" + crl_no + " or higher is already in the database");
            }
        }
        log.info("\nSummary:\nRevoked " + revoked + " certificates");
        if (already_revoked > 0) {
            log.info(already_revoked + " certificates were already revoked");
        }
        if (miss_count > 0) {
            log.info("There were " + miss_count
                    + (adaptive ? " dummy certificates added to" : " certificates missing in")
                    + " the database");
        }
        log.info("CRL #" + crl_no + " stored in the database");
    } catch (Exception e) {
        //FIXME: This is all kinds of suboptimal.
        log.info("Error: " + e.getMessage());
        return CommandResult.FUNCTIONAL_FAILURE;
    }
    log.trace("<execute()");
    return CommandResult.SUCCESS;
}

From source file:org.ejbca.ui.cli.ca.CaInitCommandTest.java

License:Open Source License

/** Test happy path for creating a CA signed by an external CA. */
@Test// w  w  w. j a v  a  2 s  . c  o  m
public void testCASignedByExternal() throws Exception {
    // Create a handmade External CA
    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    X509Certificate externalCACert = CertTools.genSelfCert("CN=External CA", 365, null, keys.getPrivate(),
            keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true);
    final String fp1 = CertTools.getFingerprintAsString(externalCACert);
    String fp2 = null;
    File temp = File.createTempFile("chain", ".pem");
    File csr = new File(CA_NAME + "_csr.der");
    File certfile = new File(CA_NAME + "_cert.der");
    try {
        ArrayList<Certificate> mylist = new ArrayList<Certificate>();
        mylist.add(externalCACert);
        FileOutputStream fos = new FileOutputStream(temp);
        fos.write(CertTools.getPemFromCertificateChain(mylist));
        fos.close();
        SIGNED_BY_EXTERNAL_ARGS[SIGNED_BY_EXTERNAL_ARGS.length - 1] = temp.getAbsolutePath();
        assertEquals(CommandResult.SUCCESS, caInitCommand.execute(SIGNED_BY_EXTERNAL_ARGS));
        CAInfo cainfo = caSession.getCAInfo(admin, CA_NAME);
        assertNotNull("CA signed by external CA was not created.", cainfo);
        assertEquals(
                "Creating a CA signed by an external CA should initially create it in status 'waiting for certificate response'",
                CAConstants.CA_WAITING_CERTIFICATE_RESPONSE, cainfo.getStatus());

        // Read the generated CSR, requires knowledge of what filename it creates
        byte[] bytes = FileTools.readFiletoBuffer(CA_NAME + "_csr.der");
        PKCS10RequestMessage msg = new PKCS10RequestMessage(bytes);
        // Create a new certificate with the subjectDN and publicKey from the request
        Date firstDate = new Date();
        Date lastDate = new Date();
        lastDate.setTime(lastDate.getTime() + (365 * (24 * 60 * 60 * 1000)));
        byte[] serno = new byte[8];
        Random random = new Random();
        random.setSeed(firstDate.getTime());
        random.nextBytes(serno);
        final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
                (ASN1Sequence) ASN1Primitive.fromByteArray(msg.getRequestPublicKey().getEncoded()));
        X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
                CertTools.stringToBcX500Name(externalCACert.getSubjectDN().toString()),
                new java.math.BigInteger(serno).abs(), firstDate, lastDate,
                CertTools.stringToBcX500Name(msg.getRequestDN()), pkinfo);
        BasicConstraints bc = new BasicConstraints(true);
        certbuilder.addExtension(Extension.basicConstraints, true, bc);
        X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
        final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480);
        final X509CertificateHolder certHolder = certbuilder.build(signer);
        final X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());
        fp2 = CertTools.getFingerprintAsString(cert);
        // Now we have issued a certificate, import it
        mylist = new ArrayList<Certificate>();
        mylist.add(cert);
        fos = new FileOutputStream(certfile);
        fos.write(CertTools.getPemFromCertificateChain(mylist));
        fos.close();
        IMPORT_SIGNED_BY_EXTERNAL_ARGS[IMPORT_SIGNED_BY_EXTERNAL_ARGS.length - 1] = certfile.getAbsolutePath();
        assertEquals(CommandResult.SUCCESS, caImportCaCertCommand.execute(IMPORT_SIGNED_BY_EXTERNAL_ARGS));
        cainfo = caSession.getCAInfo(admin, CA_NAME);
        assertNotNull("CA signed by external CA does not exist.", cainfo);
        assertEquals(
                "importing a certificate to a CA signed by an external CA should result in status 'active'",
                CAConstants.CA_ACTIVE, cainfo.getStatus());
    } finally {
        temp.deleteOnExit();
        csr.deleteOnExit();
        certfile.deleteOnExit();
        // Clean up imported certificates from database
        internalCertStoreSession.removeCertificate(fp1);
        internalCertStoreSession.removeCertificate(fp2);
    }
}

From source file:org.ejbca.ui.cli.ca.CaRestoreKeyStoreCommand.java

License:Open Source License

@Override
public CommandResult execute(ParameterContainer parameters) {
    String kspwd = parameters.get(KEYSTORE_PASSWORD_KEY);
    String caName = parameters.get(CA_NAME_KEY);
    // Import soft keystore
    String p12file = parameters.get(PKCS12_FILE_KEY);
    String alias = parameters.get(SIG_ALIAS_KEY);
    String encryptionAlias = parameters.get(ENC_ALIAS_KEY);
    if (kspwd == null) {
        getLogger().info("Enter keystore password: ");
        // Read the password, but mask it so we don't display it on the console
        kspwd = String.valueOf(System.console().readPassword());
    } else {//from  www  . jav a  2  s  . c o  m
        getLogger().info("Keystore password was supplied on the command line.");
    }
    // Read old keystore file in the beginning so we know it's good
    byte[] keystorebytes = null;
    try {
        keystorebytes = FileTools.readFiletoBuffer(p12file);
    } catch (FileNotFoundException e) {
        log.error("File " + p12file + " was not found.");
        return CommandResult.FUNCTIONAL_FAILURE;
    }
    // Import CA from PKCS12 file
    if (alias == null) {
        // First we must find what aliases there is in the pkcs12-file
        KeyStore ks;
        try {
            ks = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
        } catch (KeyStoreException e) {
            throw new IllegalStateException("PKCS#12 implementation not found.", e);
        } catch (NoSuchProviderException e) {
            throw new IllegalStateException("BouncyCastle provider not found.", e);
        }
        FileInputStream fis;
        try {
            fis = new FileInputStream(p12file);
        } catch (FileNotFoundException e) {
            log.error("File " + p12file + " was not found.");
            return CommandResult.FUNCTIONAL_FAILURE;
        }
        try {
            ks.load(fis, kspwd.toCharArray());
            fis.close();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(
                    "Algorithm used to check the integrity of the keystore could npt be found.", e);
        } catch (CertificateException e) {
            throw new IllegalStateException("Certificate could not be loaded from keystore.", e);
        } catch (IOException e) {
            throw new IllegalStateException("Unknown IOException was caught.", e);
        }

        Enumeration<String> aliases;
        try {
            aliases = ks.aliases();
        } catch (KeyStoreException e) {
            throw new IllegalStateException("Keystore was not initialized", e);
        }
        int length = 0;
        while (aliases.hasMoreElements()) {
            alias = aliases.nextElement();
            getLogger().info("Keystore contains alias: " + alias);
            length++;
        }
        if (length > 1) {
            log.error("Keystore contains more than one alias, alias must be provided as argument.");
            return CommandResult.FUNCTIONAL_FAILURE;
        } else if (length < 1) {
            log.error("Keystore does not contain any aliases. It can not be used for a CA.");
            return CommandResult.FUNCTIONAL_FAILURE;
        }
        // else alias already contains the only alias, so we can use that
    }
    EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class).restoreCAKeyStore(
            getAuthenticationToken(), caName, keystorebytes, kspwd, kspwd, alias, encryptionAlias);
    return CommandResult.SUCCESS;

}

From source file:org.ejbca.ui.web.admin.cainterface.CADataHandler.java

License:Open Source License

/**
 *  @see org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean
 *///from w  w w. j a v a 2s .  co m
public void importCAFromKeyStore(String caname, byte[] p12file, String keystorepass,
        String privateSignatureKeyAlias, String privateEncryptionKeyAlias) throws Exception {
    final KeyStore ks = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
    ks.load(new ByteArrayInputStream(p12file), keystorepass.toCharArray());
    if (privateSignatureKeyAlias.equals("")) {
        Enumeration<String> aliases = ks.aliases();
        if (aliases == null || !aliases.hasMoreElements()) {
            throw new Exception("This file does not contain any aliases.");
        }
        privateSignatureKeyAlias = (String) aliases.nextElement();
        if (aliases.hasMoreElements()) {
            while (aliases.hasMoreElements()) {
                privateSignatureKeyAlias += " " + (String) aliases.nextElement();
            }
            throw new Exception(
                    "You have to specify any of the following aliases: " + privateSignatureKeyAlias);
        }
    }
    if (privateEncryptionKeyAlias.equals("")) {
        privateEncryptionKeyAlias = null;
    }
    caadminsession.importCAFromKeyStore(administrator, caname, p12file, keystorepass, keystorepass,
            privateSignatureKeyAlias, privateEncryptionKeyAlias);
    info.cAsEdited();
}

From source file:org.ejbca.ui.web.admin.keybind.InternalKeyBindingMBean.java

License:Open Source License

/** @return list of gui representations for all the InternalKeyBindings of the current type*/
public ListDataModel<GuiInfo> getInternalKeyBindingGuiList() {
    if (internalKeyBindingGuiList == null) {
        // Get the current type of tokens we operate on
        final String internalKeyBindingType = getSelectedInternalKeyBindingType();
        List<GuiInfo> internalKeyBindingList = new LinkedList<GuiInfo>();
        for (InternalKeyBindingInfo current : internalKeyBindingSession
                .getInternalKeyBindingInfos(authenticationToken, internalKeyBindingType)) {
            final int cryptoTokenId = current.getCryptoTokenId();
            final CryptoTokenInfo cryptoTokenInfo = cryptoTokenManagementSession
                    .getCryptoTokenInfo(cryptoTokenId);
            final String cryptoTokenName;
            boolean cryptoTokenAvailable = false;
            boolean cryptoTokenActive = false;
            if (cryptoTokenInfo == null) {
                cryptoTokenName = "unknown";
            } else {
                cryptoTokenAvailable = accessControlSession.isAuthorizedNoLogging(authenticationToken,
                        CryptoTokenRules.GENERATE_KEYS.resource() + "/" + cryptoTokenId);
                cryptoTokenActive = cryptoTokenInfo.isActive();
                cryptoTokenName = cryptoTokenInfo.getName();
            }//ww w . ja v a 2  s . c  om
            final String certificateId = current.getCertificateId();
            final Certificate certificate = certificateId == null ? null
                    : certificateStoreSession.findCertificateByFingerprint(certificateId);
            String certificateIssuerDn = "";
            String certificateSubjectDn = "";
            String certificateSerialNumber = "";
            String caCertificateIssuerDn = "";
            String caCertificateSerialNumber = "";
            String certificateInternalCaName = null;
            int certificateInternalCaId = 0;
            String status = current.getStatus().name();
            if (certificate != null) {
                certificateSubjectDn = CertTools.getSubjectDN(certificate);
                certificateIssuerDn = CertTools.getIssuerDN(certificate);
                certificateSerialNumber = CertTools.getSerialNumberAsString(certificate);
                try {
                    // Note that we can do lookups using the .hashCode, but we will use the objects id
                    final CA ca = caSession.getCANoLog(authenticationToken, certificateIssuerDn.hashCode());
                    certificateInternalCaName = ca.getName();
                    certificateInternalCaId = ca.getCAId();
                    caCertificateIssuerDn = CertTools.getIssuerDN(ca.getCACertificate());
                    caCertificateSerialNumber = CertTools.getSerialNumberAsString(ca.getCACertificate());
                    // Check that the current CA certificate is the issuer of the IKB certificate
                    certificate.verify(ca.getCACertificate().getPublicKey(),
                            BouncyCastleProvider.PROVIDER_NAME);
                } catch (CADoesntExistsException | AuthorizationDeniedException | InvalidKeyException
                        | CertificateException | NoSuchAlgorithmException | NoSuchProviderException
                        | SignatureException e) {
                    // The CA is for the purpose of "internal" renewal not available to this administrator.
                    // Try to find the issuer (CA) certificate by other means, trying to get it through CA certificate link from the bound certificate 
                    CertificateInfo info = certificateStoreSession.getCertificateInfo(certificateId);
                    final Certificate cacertificate = info.getCAFingerprint() == null ? null
                            : certificateStoreSession.findCertificateByFingerprint(info.getCAFingerprint());
                    if (cacertificate != null) {
                        caCertificateIssuerDn = CertTools.getIssuerDN(cacertificate);
                        caCertificateSerialNumber = CertTools.getSerialNumberAsString(cacertificate);
                    }
                }
                // Check for additional informative UI states
                if (InternalKeyBindingStatus.ACTIVE.equals(current.getStatus())) {
                    // Check if certificate is expired
                    if (certificate instanceof X509Certificate) {
                        final X509Certificate x509Certificate = (X509Certificate) certificate;
                        try {
                            x509Certificate.checkValidity();
                            // Check if certificate is revoked
                            if (certificateStoreSession.isRevoked(certificateIssuerDn,
                                    x509Certificate.getSerialNumber())) {
                                status = "REVOKED";
                            }
                        } catch (CertificateExpiredException e) {
                            status = "EXPIRED";
                        } catch (CertificateNotYetValidException e) {
                            status = "NOTYETVALID";
                        }
                    }
                }
            }
            internalKeyBindingList.add(new GuiInfo(current.getId(), current.getName(), cryptoTokenId,
                    cryptoTokenName, cryptoTokenAvailable, cryptoTokenActive, current.getKeyPairAlias(),
                    current.getNextKeyPairAlias(), status, current.getCertificateId(), certificateIssuerDn,
                    certificateSubjectDn, certificateInternalCaName, certificateInternalCaId,
                    certificateSerialNumber, caCertificateIssuerDn, caCertificateSerialNumber));
            Collections.sort(internalKeyBindingList, new Comparator<GuiInfo>() {
                @Override
                public int compare(final GuiInfo guiInfo1, final GuiInfo guiInfo2) {
                    return guiInfo1.getName().compareToIgnoreCase(guiInfo2.getName());
                }
            });
        }
        internalKeyBindingGuiList = new ListDataModel<GuiInfo>(internalKeyBindingList);
    }
    // View the list will purge the view cache
    flushSingleViewCache();
    return internalKeyBindingGuiList;
}

From source file:org.ejbca.ui.web.RequestHelperTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Test/*from   ww w .  j  av a  2s  .c  o m*/
public void testPkcs10CertRequestWithCertificateChain() throws Exception {
    RequestHelper requestHelper = new RequestHelper(null, null);

    //Generate a self signed certificate to act as a CA cert, and a signed certificate.
    KeyPair caKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    Certificate caCert = CertTools.genSelfCert("CN=foo", 365, null, caKeys.getPrivate(), caKeys.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);
    KeyPair replyKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
            (ASN1Sequence) ASN1Primitive.fromByteArray(replyKeys.getPublic().getEncoded()));
    String signedCertDn = "CN=signedcert";
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);
    Date firstDate = new Date();
    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));
    Date lastDate = new Date();
    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (24 * 60 * 60 * 1000));
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name("CN=foo"),
            new java.math.BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(signedCertDn), pkinfo);
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(caKeys.getPrivate()),
            20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate signedCert = (X509Certificate) CertTools
            .getCertfromByteArray(certHolder.getEncoded());

    //Setup mocks
    SignSessionLocal signsession = EasyMock.createMock(SignSessionLocal.class);
    ResponseMessage responseMessage = EasyMock.createMock(X509ResponseMessage.class);
    //EasyMock.expect(signsession.createCertificate(authenticationToken, EasyMock.anyObject(RequestMessage.class), X509ResponseMessage.class, null)).andReturn(responseMessage);
    EasyMock.expect(signsession.createCertificate(EasyMock.anyObject(AuthenticationToken.class),
            EasyMock.anyObject(RequestMessage.class), EasyMock.anyObject(X509ResponseMessage.class.getClass()),
            EasyMock.anyObject(EndEntityInformation.class))).andReturn(responseMessage);
    EasyMock.expect(responseMessage.getResponseMessage()).andReturn(signedCert.getEncoded());
    CaSessionLocal caSession = EasyMock.createMock(CaSessionLocal.class);
    CA ca = EasyMock.createMock(CA.class);
    EasyMock.expect(signsession.getCAFromRequest(EasyMock.anyObject(AuthenticationToken.class),
            EasyMock.anyObject(RequestMessage.class), EasyMock.anyBoolean())).andReturn(ca);
    CAInfo caInfo = EasyMock.createMock(CAInfo.class);
    EasyMock.expect(ca.getCAInfo()).andReturn(caInfo);
    EasyMock.expect(caInfo.getCertificateChain()).andReturn(Arrays.asList(caCert));
    EasyMock.replay(caInfo, ca, responseMessage, signsession, caSession);

    //Perform test
    byte[] result = requestHelper.pkcs10CertRequest(signsession, caSession, PRE_GENERATED_CSR, "foo", "foo123",
            CertificateResponseType.ENCODED_CERTIFICATE_CHAIN).getEncoded();
    List<Certificate> certChain = CertTools.getCertsFromPEM(new ByteArrayInputStream(result));
    assertEquals(signedCert, certChain.get(0));
    assertEquals(caCert, certChain.get(1));

    //Verify that mocks have behaved as planned
    EasyMock.verify(caInfo, ca, responseMessage, signsession, caSession);
}

From source file:org.ejbca.util.CMS.java

License:Open Source License

/**
 * @param is data to be decrypted//from www  . j av a  2  s .com
 * @param os decrypted data
 * @param key to be used for the decryption
 * @param providerName the provider that should do the decryption
 * @throws Exception
 */
public static void decrypt(final InputStream is, OutputStream os, PrivateKey key, String providerName)
        throws Exception {
    final InputStream bis = new BufferedInputStream(is, bufferSize);
    final OutputStream bos = new BufferedOutputStream(os, bufferSize);
    @SuppressWarnings("unchecked")
    final Iterator<RecipientInformation> it = new CMSEnvelopedDataParser(bis).getRecipientInfos()
            .getRecipients().iterator();
    if (it.hasNext()) {
        final RecipientInformation recipientInformation = it.next();
        JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key);
        rec.setProvider(providerName);
        rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
        final CMSTypedStream recData = recipientInformation.getContentStream(rec);
        final InputStream ris = recData.getContentStream();
        fromInToOut(ris, bos);
    }
    os.close();
}

From source file:org.ejbca.util.CMS.java

License:Open Source License

/**
 * @param is data to be signed/*  ww w.  j a  va 2  s. c o m*/
 * @param os signed data
 * @param key to do be used for signing
 * @param providerName the provider that should do the signing
 * @throws Exception
 */
public static void sign(final InputStream is, OutputStream os, PrivateKey key, String providerName,
        X509Certificate cert) throws Exception {
    final InputStream bis = new BufferedInputStream(is, bufferSize);
    final OutputStream bos = new BufferedOutputStream(os, bufferSize);
    final CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator();
    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
    JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
            calculatorProviderBuilder.build());
    final String digest = CMSSignedGenerator.DIGEST_SHA256;
    String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digest, key.getAlgorithm());
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName).setProvider(providerName)
            .build(key);
    if (cert != null) {
        gen.addSignerInfoGenerator(builder.build(contentSigner, cert));
    } else {
        gen.addSignerInfoGenerator(builder.build(contentSigner, "hej".getBytes()));
    }
    final OutputStream out = gen.open(bos, true);
    fromInToOut(bis, out);
    bos.close();
    os.close();
}

From source file:org.ejbca.util.CMS.java

License:Open Source License

/**
 * @param is signed data to be verified//from w  w w .  j a  v  a  2 s.  c  o  m
 * @param os signature removed from signed data
 * @param cert the certificate with the public key that should do the verification
 * @return true if the signing was to with the private key corresponding to the public key in the certificate.
 * @throws Exception
 */
public static VerifyResult verify(final InputStream is, OutputStream os, X509Certificate cert)
        throws Exception {
    final InputStream bis = new BufferedInputStream(is, bufferSize);
    final OutputStream bos = new BufferedOutputStream(os, bufferSize);
    final CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), bis);
    final CMSTypedStream sc = sp.getSignedContent();
    final InputStream ris = sc.getContentStream();
    fromInToOut(ris, bos);
    os.close();
    sc.drain();
    @SuppressWarnings("rawtypes")
    final Iterator it = sp.getSignerInfos().getSigners().iterator();
    if (!it.hasNext()) {
        return null;
    }
    final SignerInformation signerInfo = (SignerInformation) it.next();
    final Attribute attribute = (Attribute) signerInfo.getSignedAttributes().getAll(CMSAttributes.signingTime)
            .get(0);
    final Date date = Time.getInstance(attribute.getAttrValues().getObjectAt(0).toASN1Primitive()).getDate();
    final SignerId id = signerInfo.getSID();
    boolean result = false;
    try {
        JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME);
        JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
                calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
        result = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cert.getPublicKey()));
    } catch (Throwable t) { // NOPMD
        log.debug("Exception when verifying", t);
    }
    return new VerifyResult(date, result, id);
}

From source file:org.ejbca.util.keystore.P12toPEM.java

License:Open Source License

/**
 * Converts a P12 into a PEM/*from   ww w. ja v a  2  s . c  o m*/
 *
 * @return the created PEM file, null if file wasn't found and no other exception was thrown. 
 *
 * @throws FileNotFoundException if the P12 file supplied to this class in its constructor was not found.
 * @throws CertificateException if the p12 couldn't be loaded
 * @throws NoSuchAlgorithmException if the algorithm used to build the P12 couldn't be found
 * @throws KeyStoreException if the keystore has not been initialised. 
 * @throws UnrecoverableKeyException if the password was incorrect 
 */
public File createPEM() throws FileNotFoundException, NoSuchAlgorithmException, CertificateException,
        KeyStoreException, UnrecoverableKeyException {
    if (this.ks == null) {
        try {
            ks = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
        } catch (NoSuchProviderException e) {
            throw new IllegalStateException("BouncyCastle provider not found.", e);
        }
        InputStream in = new FileInputStream(p12File);
        try {
            try {
                ks.load(in, password.toCharArray());
            } finally {
                in.close();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Unexpected IOException was thrown", e);
        }
    }
    // Fid the key private key entry in the keystore
    Enumeration<String> e = ks.aliases();
    Object o = null;
    PrivateKey serverPrivKey = null;

    while (e.hasMoreElements()) {
        o = e.nextElement();

        if (o instanceof String) {
            if ((ks.isKeyEntry((String) o))
                    && ((serverPrivKey = (PrivateKey) ks.getKey((String) o, password.toCharArray())) != null)) {
                if (log.isDebugEnabled()) {
                    log.debug("Aliases " + o + " is KeyEntry.");
                }
                break;
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug((("Private key encode: " + serverPrivKey) == null) ? null : serverPrivKey.getFormat());
    }
    byte[] privKeyEncoded = "".getBytes();
    if (serverPrivKey != null) {
        privKeyEncoded = serverPrivKey.getEncoded();
    }
    Certificate[] chain = KeyTools.getCertChain(ks, (String) o);
    if (log.isDebugEnabled()) {
        log.debug("Loaded certificate chain with length " + chain.length + " from keystore.");
    }
    X509Certificate userX509Certificate = (X509Certificate) chain[0];

    byte[] output = userX509Certificate.getEncoded();
    String sn = CertTools.getSubjectDN(userX509Certificate);
    String userFile = CertTools.getPartFromDN(sn, "CN");
    String filetype = ".pem";

    File path = new File(exportpath);
    path.mkdir();

    File tmpFile = new File(path, userFile + filetype);

    OutputStream out = new FileOutputStream(tmpFile);
    try {
        try {
            out.write(beginCertificate);
            out.write(NL);
            byte[] userCertB64 = Base64.encode(output);
            out.write(userCertB64);
            out.write(NL);
            out.write(endCertificate);
        } finally {
            out.close();
        }
    } catch (IOException e1) {
        throw new IllegalStateException("Unexpected IOException was thrown", e1);
    }

    tmpFile = new File(path, userFile + "-Key" + filetype);

    out = new FileOutputStream(tmpFile);
    try {
        try {
            out.write(beginPrivateKey);
            out.write(NL);
            byte[] privKey = Base64.encode(privKeyEncoded);
            out.write(privKey);
            out.write(NL);
            out.write(endPrivateKey);
        } finally {
            out.close();
        }
    } catch (IOException e1) {
        throw new IllegalStateException("Unexpected IOException was thrown", e1);
    }

    tmpFile = new File(path, userFile + "-CA" + filetype);

    if (CertTools.isSelfSigned(userX509Certificate)) {
        log.info("User certificate is selfsigned, this is a RootCA, no CA certificates written.");
    } else {
        out = new FileOutputStream(tmpFile);
        try {
            for (int num = 1; num < chain.length; num++) {
                X509Certificate tmpX509Cert = (X509Certificate) chain[num];
                byte[] tmpOutput = tmpX509Cert.getEncoded();
                try {
                    out.write(beginCertificate);
                    out.write(NL);

                    byte[] tmpCACertB64 = Base64.encode(tmpOutput);

                    out.write(tmpCACertB64);
                    out.write(NL);
                    out.write(endCertificate);
                    out.write(NL);
                } catch (IOException e1) {
                    throw new IllegalStateException("Unexpected IOException was thrown", e1);
                }
            }

        } finally {
            try {
                out.close();
            } catch (IOException e1) {
                throw new IllegalStateException("Unexpected IOException was thrown", e1);
            }
        }
    }
    return tmpFile;
}