Example usage for java.security.cert Certificate getEncoded

List of usage examples for java.security.cert Certificate getEncoded

Introduction

In this page you can find the example usage for java.security.cert Certificate getEncoded.

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

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

/**
 * Handles PKCS10 certificate request, these are constructed as: <code> CertificationRequest
 * ::= SEQUENCE { certificationRequestInfo  CertificationRequestInfo, signatureAlgorithm
 * AlgorithmIdentifier{{ SignatureAlgorithms }}, signature                       BIT STRING }
 * CertificationRequestInfo ::= SEQUENCE { version             INTEGER { v1(0) } (v1,...),
 * subject             Name, subjectPKInfo   SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
 * attributes          [0] Attributes{{ CRIAttributes }}} SubjectPublicKeyInfo { ALGORITHM :
 * IOSet} ::= SEQUENCE { algorithm           AlgorithmIdentifier {{IOSet}}, subjectPublicKey
 * BIT STRING }</code> PublicKey's encoded-format has to be RSA X.509.
 *
 * @param signsession signsession to get certificate from
 * @param caSession a reference to CaSessionBean
 * @param b64Encoded base64 encoded pkcs10 request message
 * @param username username of requesting user
 * @param password password of requesting user
 * @param resulttype should indicate if a PKCS7 or just the certificate is wanted.
 * @param doSplitLines/*from   w  ww  .jav a  2s  . c  o  m*/
 * @return Base64 encoded byte[] 
 * @throws AuthorizationDeniedException 
 * @throws CesecoreException 
 * @throws EjbcaException 
 * @throws CertificateException 
 * @throws CertificateEncodingException 
 * @throws CertificateExtensionException if b64Encoded specified invalid extensions
 */
public CertificateRequestResponse pkcs10CertRequest(SignSessionLocal signsession, CaSessionLocal caSession,
        byte[] b64Encoded, String username, String password, CertificateResponseType resulttype,
        boolean doSplitLines) throws EjbcaException, CesecoreException, AuthorizationDeniedException,
        CertificateEncodingException, CertificateException, CertificateExtensionException {
    byte[] encoded = null;
    Certificate cert = null;
    PKCS10RequestMessage req = RequestMessageUtils.genPKCS10RequestMessage(b64Encoded);
    req.setUsername(username);
    req.setPassword(password);
    ResponseMessage resp = signsession.createCertificate(administrator, req, X509ResponseMessage.class, null);
    cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    switch (resulttype) {
    case ENCODED_CERTIFICATE:
        encoded = Base64.encode(cert.getEncoded(), doSplitLines);
        break;
    case ENCODED_CERTIFICATE_CHAIN:
        CAInfo caInfo = signsession.getCAFromRequest(administrator, req, false).getCAInfo();
        LinkedList<Certificate> chain = new LinkedList<Certificate>(caInfo.getCertificateChain());
        chain.addFirst(cert);
        encoded = CertTools.getPemFromCertificateChain(chain);
        break;
    case ENCODED_PKCS7:
        encoded = Base64.encode(signsession.createPKCS7(administrator, cert, true), doSplitLines);
        break;
    default:
        break;
    }
    log.debug("Created certificate (PKCS7) for " + username);
    if (debug != null) {
        debug.print("<h4>Generated certificate:</h4>");
        debug.printInsertLineBreaks(cert.toString().getBytes());
    }
    return new CertificateRequestResponse(cert, encoded);
}

From source file:org.cesecore.certificates.ca.CA.java

public void setRequestCertificateChain(Collection<Certificate> requestcertificatechain) {
    final ArrayList<String> storechain = new ArrayList<String>();
    for (final Certificate cert : requestcertificatechain) {
        try {/*w w w .j ava 2  s.  c  o m*/
            storechain.add(new String(Base64.encode(cert.getEncoded())));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    data.put(REQUESTCERTCHAIN, storechain);
    this.requestcertchain = new ArrayList<Certificate>();
    this.requestcertchain.addAll(requestcertificatechain);
}

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

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is
 * set to 'privateKey' and the private key password is null.
 *
 * @param alias the alias used for the key entry
 * @param privKey RSA private key/* w  w  w  . j  av  a  2 s .  c om*/
 * @param cert user certificate
 * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i;
                }
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i);
                }
                if (cafriendly == null) {
                    cafriendly = "CA_unknown" + i;
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

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

public CrmfRequestTest(String arg0) throws CertificateEncodingException, CertificateException {
    super(arg0);/*from  ww w. ja v a 2s .c o  m*/
    admin = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER);
    CryptoProviderTools.installBCProvider();
    // Try to use AdminCA1 if it exists
    CAInfo adminca1 = caAdminSession.getCAInfo(admin, "AdminCA1");
    if (adminca1 == null) {
        Collection<Integer> caids = caSession.getAvailableCAs(admin);
        Iterator<Integer> iter = caids.iterator();
        while (iter.hasNext()) {
            caid = iter.next().intValue();
        }
    } else {
        caid = adminca1.getCAId();
    }
    if (caid == 0) {
        assertTrue("No active CA! Must have at least one active CA to run tests!", false);
    }
    CAInfo cainfo = caAdminSession.getCAInfo(admin, caid);
    Collection<Certificate> certs = cainfo.getCertificateChain();
    if (certs.size() > 0) {
        Iterator<Certificate> certiter = certs.iterator();
        Certificate cert = certiter.next();
        String subject = CertTools.getSubjectDN(cert);
        if (StringUtils.equals(subject, cainfo.getSubjectDN())) {
            // Make sure we have a BC certificate
            cacert = (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
        }
    } else {
        log.error("NO CACERT for caid " + caid);
    }
    issuerDN = cacert.getIssuerDN().getName();
    log.debug("issuerDN: " + issuerDN);
    log.debug("caid: " + caid);
    updatePropertyOnServer(CmpConfiguration.CONFIG_OPERATIONMODE, "normal");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RESPONSEPROTECTION, "signature");
    updatePropertyOnServer(CmpConfiguration.CONFIG_DEFAULTCA, issuerDN);
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONMODULE,
            CmpConfiguration.AUTHMODULE_HMAC + ";" + CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD);
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONPARAMETERS, "-;-");
}

From source file:org.signserver.module.pdfsigner.PDFSigner.java

/**
 * Calculates an estimate of the PKCS#7 structure size given the provided  
 * input parameters./*from   w w w  .  j  ava2  s .  c  o m*/
 *
 * Questions that we need to answer to construct an formula for calculating 
 * a good enough estimate:
 *
 * 1. What are the parameters influencing the PKCS#7 size?
 *    - static or depending on algorithms: PKCS#7 signature size, 
 *    - Certificates list
 *    - CRL list
 *    - OCSP bytes
 *    - timestamp response
 *
 * 2. How much does the size increase when the size of an certificate increases?
 *    - It appears to be at maximum the same increase in size
 *
 * 3. How much does the size increase for each new certificate, not including the certificate size?
 *    - 0. No increase for each certificate except the actual certificate size
 *
 * 4. How much does the size increase when the size of the timestamp responses increases?
 *    - It appears to be at maximum the same increase in size
 *    - However as the response is sent after the signing and possibly 
 *      from an external server we can not be sure about what size it 
 *      will have. We should use a large enough (but reasonable) value that 
 *      it is not so likely that we will have to do a second try.
 * 
 * 5. How much does the size increase when the size of an CRL increases?
 *    - It appears to be the same increase in size most of the times but in
 *      in one case it got 1 byte larger.
 *    - It turns out that the CRLs are included twice (!)
 *    
 * 6. How much does the size increase for each new CRL, not including the CRL size?
 *    - 0. No increase for each CRL except the actual CRL size
 *
 * 7. What is a typical size of an timestamp response?
 *    - That depends mostly on the included certificate chain
 *
 * 8. What value should we use in the initial estimate for the timestamp?
 *    - Currently 4096 is used but with a chain of 4 "normal" certificates
 *      that is a little bit too little.
 *    - Lets use 7168 and there are room for about 6 "normal" certificates
 * 
 * 
 * See also PDFSignerUnitTest for tests that the answers to the questions 
 * above still holds.
 * @param certChain The signing certificate chain
 * @param tsc Timestamp client, this can be null if no timestamp response is used. The contribution is estimated by using a fixed value
 * @param ocsp The OCSP response, can be null
 * @param crlList The list of CRLs included in the signature, this can be null
 * 
 * @return Returns the estimated signature size in bytes
 */
protected int calculateEstimatedSignatureSize(Certificate[] certChain, TSAClient tsc, byte[] ocsp,
        CRL[] crlList) throws SignServerException {
    int estimatedSize = 0;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Calculating estimated signature size");
    }

    for (Certificate cert : certChain) {
        try {
            int certSize = cert.getEncoded().length;
            estimatedSize += certSize;

            if (LOG.isDebugEnabled()) {
                LOG.debug("Adding " + certSize + " bytes for certificate");
            }

        } catch (CertificateEncodingException e) {
            throw new SignServerException("Error estimating signature size contribution for certificate", e);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Total size of certificate chain: " + estimatedSize);
    }

    // add estimate for PKCS#7 structure + hash
    estimatedSize += 2000;

    // add space for OCSP response
    if (ocsp != null) {
        estimatedSize += ocsp.length;

        if (LOG.isDebugEnabled()) {
            LOG.debug("Adding " + ocsp.length + " bytes for OCSP response");
        }
    }

    if (tsc != null) {
        // add guess for timestamp response (which we can't really know)
        // TODO: we might be able to store the size of the last TSA response and re-use next time...
        final int tscSize = 4096;

        estimatedSize += tscSize;

        if (LOG.isDebugEnabled()) {
            LOG.debug("Adding " + tscSize + " bytes for TSA");
        }
    }

    // add estimate for CRL
    if (crlList != null) {
        for (CRL crl : crlList) {
            if (crl instanceof X509CRL) {
                X509CRL x509Crl = (X509CRL) crl;

                try {
                    int crlSize = x509Crl.getEncoded().length;
                    // the CRL is included twice in the signature...
                    estimatedSize += crlSize * 2;

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Adding " + crlSize * 2 + " bytes for CRL");
                    }

                } catch (CRLException e) {
                    throw new SignServerException("Error estimating signature size contribution for CRL", e);
                }
            }
        }
        estimatedSize += 100;
    }

    return estimatedSize;
}

From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java

/**
 * Helper method to add public certificate to JWT_HEADER to signature verification.
 *
 * @param tenantDomain/*from  w ww .ja  v  a  2s. c  om*/
 * @param tenantId
 * @throws IdentityOAuth2Exception
 */
public static String getThumbPrint(String tenantDomain, int tenantId) throws IdentityOAuth2Exception {

    try {

        Certificate certificate = getCertificate(tenantDomain, tenantId);

        // TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization

        //generate the SHA-1 thumbprint of the certificate
        MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
        byte[] der = certificate.getEncoded();
        digestValue.update(der);
        byte[] digestInBytes = digestValue.digest();

        String publicCertThumbprint = hexify(digestInBytes);
        String base64EncodedThumbPrint = new String(
                new Base64(0, null, true).encode(publicCertThumbprint.getBytes(Charsets.UTF_8)),
                Charsets.UTF_8);
        return base64EncodedThumbPrint;

    } catch (Exception e) {
        String error = "Error in obtaining certificate for tenant " + tenantDomain;
        throw new IdentityOAuth2Exception(error, e);
    }
}

From source file:eu.operando.operandoapp.OperandoProxyStatus.java

private void installCert()
        throws RootCertificateException, GeneralSecurityException, OperatorCreationException, IOException {

    new AsyncTask<Void, Void, Certificate>() {
        Exception error;//from   w ww  .j  a  v  a 2  s.c om
        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MainActivity.this, null, "Generating SSL certificate...");
            dialog.setCancelable(false);
        }

        @Override
        protected Certificate doInBackground(Void... params) {
            try {
                Certificate cert = BouncyCastleSslEngineSource
                        .initializeKeyStoreStatic(mainContext.getAuthority());
                return cert;
            } catch (Exception e) {
                error = e;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Certificate certificate) {
            dialog.dismiss();
            if (certificate != null) {
                Intent intent = KeyChain.createInstallIntent();
                try {
                    intent.putExtra(KeyChain.EXTRA_CERTIFICATE, certificate.getEncoded());
                } catch (CertificateEncodingException e) {
                    e.printStackTrace();
                }
                intent.putExtra(KeyChain.EXTRA_NAME, mainContext.getAuthority().commonName());
                startActivityForResult(intent, 1);
            } else {
                Toast.makeText(MainActivity.this, "Failed to load certificates, exiting: " + error.getMessage(),
                        Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }.execute();

}

From source file:org.ejbca.ui.web.pub.CertDistServlet.java

/**
 * handles http get//www  . j  ava2s. co m
 *
 * @param req servlet request
 * @param res servlet response
 *
 * @throws IOException input/output error
 * @throws ServletException error
 */
public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws java.io.IOException, ServletException {
    log.trace(">doGet()");

    String command;
    // Keep this for logging.
    String remoteAddr = req.getRemoteAddr();
    final AuthenticationToken administrator = new AlwaysAllowLocalAuthenticationToken(
            new UsernamePrincipal("PublicWeb: " + remoteAddr));
    //Admin administrator = new Admin(Admin.TYPE_PUBLIC_WEB_USER, remoteAddr);

    RequestHelper.setDefaultCharacterEncoding(req);
    String issuerdn = null;
    if (req.getParameter(ISSUER_PROPERTY) != null) {
        // HttpServetRequets.getParameter URLDecodes the value for you
        // No need to do it manually, that will cause problems with + characters
        issuerdn = req.getParameter(ISSUER_PROPERTY);
        issuerdn = CertTools.stringToBCDNString(issuerdn);
    }
    int caid = 0;
    if (req.getParameter(CAID_PROPERTY) != null) {
        caid = Integer.parseInt(req.getParameter(CAID_PROPERTY));
    }
    // See if the client wants the response cert or CRL in PEM format (default is DER)
    String format = req.getParameter(FORMAT_PROPERTY);
    command = req.getParameter(COMMAND_PROPERTY_NAME);
    if (command == null) {
        command = "";
    }
    if ((command.equalsIgnoreCase(COMMAND_CRL) || command.equalsIgnoreCase(COMMAND_DELTACRL))
            && issuerdn != null) {
        try {
            byte[] crl = null;
            if (command.equalsIgnoreCase(COMMAND_CRL)) {
                crl = crlSession.getLastCRL(issuerdn, false); // CRL
            } else {
                crl = crlSession.getLastCRL(issuerdn, true); // deltaCRL
            }
            X509CRL x509crl = CertTools.getCRLfromByteArray(crl);
            String dn = CertTools.getIssuerDN(x509crl);
            // We must remove cache headers for IE
            ServletUtils.removeCacheHeaders(res);
            // moz is only kept for backwards compatibility, can be removed in EJBCA 6.4 or 6.5
            String moz = req.getParameter(MOZILLA_PROPERTY);
            String filename = CertTools.getPartFromDN(dn, "CN") + ".crl";
            if (command.equalsIgnoreCase(COMMAND_DELTACRL)) {
                filename = "delta_" + filename;
            }
            if ((moz == null) || !moz.equalsIgnoreCase("y")) {
                res.setHeader("Content-disposition",
                        "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
            }
            res.setContentType("application/x-x509-crl");
            if (StringUtils.equals(format, "PEM")) {
                RequestHelper.sendNewB64File(Base64.encode(crl, true), res, filename,
                        RequestHelper.BEGIN_CRL_WITH_NL, RequestHelper.END_CRL_WITH_NL);
            } else {
                res.setContentLength(crl.length);
                res.getOutputStream().write(crl);
            }
            log.debug("Sent latest CRL to client at " + remoteAddr);
        } catch (Exception e) {
            log.debug("Error sending latest CRL to " + remoteAddr + ": ", e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting latest CRL.");
            return;
        }
    } else if (command.equalsIgnoreCase(COMMAND_EECERT)) {
        // HttpServetRequets.getParameter URLDecodes the value for you
        // No need to do it manually, that will cause problems with + characters
        String dn = req.getParameter(ISSUER_PROPERTY);
        if (dn == null) {
            log.debug("Bad request, no 'issuer' arg to 'eecert'.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Usage command=eecert?issuer=<issuerdn>&serno=<serialnumber in hex>.");
            return;
        }
        String serno = req.getParameter(SERNO_PROPERTY);
        if (serno == null) {
            log.debug("Bad request, no 'serno' arg to 'eeceert'.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Usage command=eecert?issuer=<issuerdn>&serno=<serialnumber in hex>.");
            return;
        }
        log.debug("Looking for certificate with issuer/serno '" + dn + "', '" + serno + "'.");
        try {
            // Serial number in hex
            Certificate cert = storesession.findCertificateByIssuerAndSerno(dn, new BigInteger(serno, 16));
            sendEndEntityCert(administrator, req, res, format, cert);
        } catch (NumberFormatException e) {
            log.debug("Error getting End Entity certificate, invalid serial number (hex): ", e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Error getting End Entity certificate, invalid serial number (hex).");
            return;
        } catch (CertificateEncodingException e) {
            log.info("Error getting End Entity certificate, invalid certificate?: ", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error getting End Entity certificate, invalid certificate.");
            return;
        } catch (NoSuchFieldException e) {
            log.info("Error getting End Entity certificate, can not get field to generate filename?: ", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error getting End Entity certificate, invalid certificate.");
            return;
        } catch (AuthorizationDeniedException e) {
            log.error("Error getting End Entity certificate, not authorized to create PKCS7: ", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error getting End Entity certificate, not authorized to create PKCS7.");
            return;
        } catch (CesecoreException e) {
            log.info(
                    "Error getting End Entity certificate, CA to create PKCS7 does not exist, or can not create PKCS7: ",
                    e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Error getting End Entity certificate, CA to create PKCS7 does not exist, or can not create PKCS7.");
            return;
        }
    } else if (command.equalsIgnoreCase(COMMAND_CERT) || command.equalsIgnoreCase(COMMAND_LISTCERT)) {
        // HttpServetRequets.getParameter URLDecodes the value for you
        // No need to do it manually, that will cause problems with + characters
        String dn = req.getParameter(SUBJECT_PROPERTY);
        if (dn == null) {
            log.debug("Bad request, no 'subject' arg to 'lastcert' or 'listcert' command.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Usage command=lastcert/listcert?subject=<subjectdn>.");
            return;
        }
        try {
            log.debug("Looking for certificates for '" + dn + "'.");
            Collection<Certificate> certcoll = storesession.findCertificatesBySubject(dn);
            Object[] certs = certcoll.toArray();
            if (command.equalsIgnoreCase(COMMAND_CERT)) {
                long maxdate = 0;
                int latestcertno = -1;
                for (int i = 0; i < certs.length; i++) {
                    if (i == 0) {
                        maxdate = CertTools.getNotBefore((Certificate) certs[i]).getTime();
                        latestcertno = 0;
                    } else if (CertTools.getNotBefore((Certificate) certs[i]).getTime() > maxdate) {
                        maxdate = CertTools.getNotBefore(((Certificate) certs[i])).getTime();
                        latestcertno = i;
                    }
                }
                Certificate certcert = null;
                if (latestcertno > -1) {
                    certcert = (Certificate) certs[latestcertno];
                }
                if (certcert == null) {
                    log.debug("No certificate found for requested subject DN. '" + dn + "'.");
                    res.sendError(HttpServletResponse.SC_NOT_FOUND,
                            "No certificate found for requested subject DN.");
                } else {
                    sendEndEntityCert(administrator, req, res, format, certcert);
                    log.debug("Sent latest certificate for '" + dn + "' to client at " + remoteAddr);
                }
            }
            if (command.equalsIgnoreCase(COMMAND_LISTCERT)) {
                res.setContentType("text/html");
                PrintWriter pout = new PrintWriter(res.getOutputStream());
                printHtmlHeader("Certificates for " + HTMLTools.htmlescape(dn), pout);
                for (int i = 0; i < certs.length; i++) {
                    Date notBefore = CertTools.getNotBefore((Certificate) certs[i]);
                    Date notAfter = CertTools.getNotAfter((Certificate) certs[i]);
                    String subject = CertTools.getSubjectDN((Certificate) certs[i]);
                    String issuer = CertTools.getIssuerDN((Certificate) certs[i]);
                    BigInteger serno = CertTools.getSerialNumber((Certificate) certs[i]);
                    pout.println("<pre>Subject:" + subject);
                    pout.println("Issuer:" + issuer);
                    pout.println("NotBefore:" + notBefore.toString());
                    pout.println("NotAfter:" + notAfter.toString());
                    pout.println("Serial number:" + serno.toString());
                    pout.println("</pre>");
                    pout.println("<a href=\"certdist?cmd=revoked&issuer=" + URLEncoder.encode(issuer, "UTF-8")
                            + "&serno=" + serno.toString() + "\">Check if certificate is revoked</a>");
                    pout.println("<hr>");

                }
                if (certs.length == 0) {
                    pout.println("No certificates exists for '" + HTMLTools.htmlescape(dn) + "'.");
                }
                printHtmlFooter(pout);
                pout.close();
            }
        } catch (Exception e) {
            log.debug("Error getting certificates for '" + dn + "' for " + remoteAddr + ": ", e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting certificates.");
            return;
        }
    } else if ((command.equalsIgnoreCase(COMMAND_NSCACERT) || command.equalsIgnoreCase(COMMAND_IECACERT)
            || command.equalsIgnoreCase(COMMAND_CACERT)) && (issuerdn != null || caid != 0)) {
        String lev = req.getParameter(LEVEL_PROPERTY);
        int level = 0;
        boolean pkcs7 = false;
        if (lev != null) {
            level = Integer.parseInt(lev);
        } else {
            pkcs7 = true;
        } // CA is level 0, next over root level 1 etc etc, -1 returns chain as PKCS7
        try {
            Certificate[] chain = null;
            chain = getCertificateChain(administrator, caid, issuerdn);
            // chain.length-1 is last cert in chain (root CA)
            if (chain.length < level) {
                PrintStream ps = new PrintStream(res.getOutputStream());
                ps.println("No CA certificate of level " + level + " exist.");
                log.debug("No CA certificate of level " + level + " exist.");
                return;
            }
            Certificate cacert = (Certificate) chain[level];
            String filename = RequestHelper.getFileNameFromCertNoEnding(cacert, "ca");
            byte[] enccert = null;
            if (pkcs7) {
                enccert = signSession.createPKCS7(administrator, cacert, true);
            } else {
                enccert = cacert.getEncoded();
            }
            if (command.equalsIgnoreCase(COMMAND_NSCACERT)) {
                res.setContentType("application/x-x509-ca-cert");
                res.setContentLength(enccert.length);
                res.getOutputStream().write(enccert);
                log.debug("Sent CA cert to NS client, len=" + enccert.length + ".");
            } else if (command.equalsIgnoreCase(COMMAND_IECACERT)) {
                // We must remove cache headers for IE
                ServletUtils.removeCacheHeaders(res);
                if (pkcs7) {
                    res.setHeader("Content-disposition",
                            "attachment; filename=\"" + StringTools.stripFilename(filename) + ".p7c\"");
                } else {
                    String ending = ".crt";
                    if (cacert instanceof CardVerifiableCertificate) {
                        ending = ".cvcert";
                    }
                    res.setHeader("Content-disposition",
                            "attachment; filename=\"" + StringTools.stripFilename(filename + ending) + "\"");
                }
                res.setContentType("application/octet-stream");
                res.setContentLength(enccert.length);
                res.getOutputStream().write(enccert);
                log.debug("Sent CA cert to IE client, len=" + enccert.length + ".");
            } else if (command.equalsIgnoreCase(COMMAND_CACERT)) {
                byte[] b64cert = Base64.encode(enccert);
                String out;
                if (pkcs7) {
                    out = "-----BEGIN PKCS7-----\n";
                } else {
                    out = "-----BEGIN CERTIFICATE-----\n";
                }
                out += new String(b64cert);
                if (pkcs7) {
                    out += "\n-----END PKCS7-----\n";
                } else {
                    out += "\n-----END CERTIFICATE-----\n";
                }
                // We must remove cache headers for IE
                ServletUtils.removeCacheHeaders(res);
                res.setHeader("Content-disposition",
                        "attachment; filename=\"" + StringTools.stripFilename(filename) + ".pem\"");
                res.setContentType("application/octet-stream");
                res.setContentLength(out.length());
                res.getOutputStream().write(out.getBytes());
                log.debug("Sent CA cert to client, len=" + out.length() + ".");
            } else {
                res.setContentType("text/plain");
                res.getOutputStream().println(
                        "Commands=" + COMMAND_NSCACERT + " || " + COMMAND_IECACERT + " || " + COMMAND_CACERT);
                return;
            }
        } catch (Exception e) {
            log.debug("Error getting CA certificates: ", e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting CA certificates.");
            return;
        }
    } else if (command.equalsIgnoreCase(COMMAND_CACHAIN) && (issuerdn != null || caid != 0)) {
        // Full certificate chain for CA was requested.
        try {
            handleCaChainCommands(administrator, issuerdn, caid, format, res);
        } catch (NoSuchFieldException e) {
            log.debug("Error getting certificates for '" + caid + "' for " + remoteAddr + ": ", e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting certificates.");
            return;
        }
    } else if (command.equalsIgnoreCase(COMMAND_REVOKED)) {
        String dn = req.getParameter(ISSUER_PROPERTY);
        if (dn == null) {
            log.debug("Bad request, no 'issuer' arg to 'revoked' command.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Usage command=revoked?issuer=<issuerdn>&serno=<serialnumber>.");
            return;
        }
        String serno = req.getParameter(SERNO_PROPERTY);
        if (serno == null) {
            log.debug("Bad request, no 'serno' arg to 'revoked' command.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Usage command=revoked?issuer=<issuerdn>&serno=<serialnumber>.");
            return;
        }
        log.debug("Looking for certificate for '" + dn + "' and serno='" + serno + "'.");
        try {
            CertificateStatus revinfo = storesession.getStatus(dn, new BigInteger(serno));
            PrintWriter pout = new PrintWriter(res.getOutputStream());
            res.setContentType("text/html");
            printHtmlHeader("Check revocation", pout);
            if (revinfo != null) {
                if (revinfo.revocationReason == RevokedCertInfo.NOT_REVOKED) {
                    pout.println("<h1>NOT REVOKED</h1>");
                    pout.println("Certificate with issuer '" + HTMLTools.htmlescape(dn)
                            + "' and serial number '" + HTMLTools.htmlescape(serno) + "' is NOT revoked.");
                } else {
                    pout.println("<h1>REVOKED</h1>");
                    pout.println("Certificate with issuer '" + HTMLTools.htmlescape(dn)
                            + "' and serial number '" + HTMLTools.htmlescape(serno) + "' is revoked.");
                    pout.println("RevocationDate is '" + revinfo.revocationDate + "' and reason '"
                            + revinfo.revocationReason + "'.");
                }
            } else {
                pout.println("<h1>CERTIFICATE DOES NOT EXIST</h1>");
                pout.println("Certificate with issuer '" + HTMLTools.htmlescape(dn) + "' and serial number '"
                        + HTMLTools.htmlescape(serno) + "' does not exist.");
            }
            printHtmlFooter(pout);
            pout.close();
        } catch (Exception e) {
            log.debug("Error checking revocation for '" + dn + "' with serno '" + serno + "': ", e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error checking revocation.");
            return;
        }
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Commands=cacert | lastcert | listcerts | crl | deltacrl | revoked && issuer=<issuerdn>");
        return;
    }

}

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

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is set to 'privateKey' and the private key password is
 * null.//  w  ww .j  av a2  s  .c  o m
 * 
 * @param alias
 *            the alias used for the key entry
 * @param privKey
 *            RSA private key
 * @param cert
 *            user certificate
 * @param cachain
 *            CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception
 *                if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O");
                    if (cafriendly == null) {
                        cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU");
                        if (cafriendly == null) {
                            cafriendly = "CA_unknown" + i;
                        } else {
                            cafriendly = cafriendly + i;
                        }
                    } else {
                        cafriendly = cafriendly + i;
                    }
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:org.ejbca.core.model.ca.publisher.GeneralPurposeCustomPublisher.java

/**
 * Writes certificate to temporary file and executes an external command
 * with the full pathname of the temporary file as argument. The temporary
 * file is the encoded form of the certificate e.g. X.509 certificates would
 * be encoded as ASN.1 DER. All parameters but cert are ignored.
 * //w  w w.  ja v a  2  s. c  o  m
 * @param cert
 *            The certificate
 * 
 */
public void revokeCertificate(AuthenticationToken admin, Certificate cert, int reason)
        throws PublisherException {
    if (log.isTraceEnabled()) {
        log.trace(">revokeCertificate, Rekoving Certificate");
    }
    // Verify initialization
    if (revokeExternalCommandFileName == null) {
        String msg = intres.getLocalizedMessage("publisher.errormissingproperty",
                revokeExternalCommandPropertyName);
        log.error(msg);
        throw new PublisherException(msg);
    }
    // Run internal method to create tempfile and run the command
    List<String> arguments = new ArrayList<>();
    arguments.add(String.valueOf(reason));
    try {
        arguments.add(CertTools.getSubjectDN(cert));
        arguments.add(CertTools.getIssuerDN(cert));
        arguments.add(CertTools.getSerialNumberAsString(cert));
        runWithTempFile(revokeExternalCommandFileName, cert.getEncoded(), revokeFailOnErrorCode,
                revokeFailOnStandardError, arguments);
    } catch (CertificateEncodingException e) {
        String msg = intres.getLocalizedMessage("publisher.errorcertconversion");
        log.error(msg);
        throw new PublisherException(msg);
    }
    if (log.isTraceEnabled()) {
        log.trace("<revokeCertificate");
    }
}