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:eu.operando.proxy.OperandoProxyStatus.java

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

    new AsyncTask<Void, Void, Certificate>() {
        Exception error;//  ww w .  jav a  2 s  . com
        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MainProxyActivity.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(MainProxyActivity.this,
                        "Failed to load certificates, exiting: " + error.getMessage(), Toast.LENGTH_LONG)
                        .show();
                finish();
            }
        }
    }.execute();

}

From source file:com.kixeye.kixmpp.client.KixmppClientTest.java

private SslContext createSslContext() throws Exception {
    Certificate cert;

    try (InputStream certStream = this.getClass().getResourceAsStream("/bogus_mina_tls.cert")) {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(certStream, "boguspw".toCharArray());
        cert = ks.getCertificate("bogus");
    }// w w w .  ja  v  a 2 s  .c  o m

    File certFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), null);
    FileOutputStream certFileOutputStream = new FileOutputStream(certFile);
    IOUtils.copy(new StringReader("-----BEGIN CERTIFICATE-----\n"), certFileOutputStream);
    IOUtils.copy(new ByteArrayInputStream(Base64.encodeBase64(cert.getEncoded())), certFileOutputStream);
    IOUtils.copy(new StringReader("\n-----END CERTIFICATE-----"), certFileOutputStream);
    certFileOutputStream.close();

    return SslContext.newClientContext(certFile);
}

From source file:org.apache.directory.server.core.security.CoreKeyStoreSpi.java

@Override
public String engineGetCertificateAlias(Certificate cert) {
    LOG.debug("engineGetCertificateAlias({}) called.", cert);

    if (cert instanceof X509Certificate) {
        LOG.debug("Certificate in alias request is X.509 based.");
        X509Certificate xcert = (X509Certificate) cert;
        if (xcert.getIssuerDN().toString().equals(TlsKeyGenerator.CERTIFICATE_PRINCIPAL_DN)) {
            return APACHEDS_ALIAS;
        }/*from w  w w .  j a va  2 s  . c o m*/
    }

    try {
        Entry entry = getTlsEntry();
        if (ArrayUtils.isEquals(cert.getEncoded(), entry.get(TlsKeyGenerator.USER_CERTIFICATE_AT).getBytes())) {
            return APACHEDS_ALIAS;
        }
    } catch (Exception e) {
        LOG.error(I18n.err(I18n.ERR_66), e);
    }

    return null;
}

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

/** If the request is a CVC request, this method adds an outer signature to the request.
 * If this request is a CVCA certificate and this is the same CVCA, this method creates a CVCA link certificate.
 * If not creating a link certificate this means that an authenticated request, CVCAuthenticatedRequest is created.
 * //from w w w . j  a v  a 2 s . c o  m
 * @see CA#signRequest(byte[], boolean, boolean)
 */
public byte[] signRequest(byte[] request, boolean usepreviouskey, boolean createlinkcert)
        throws CATokenOfflineException {
    if (log.isTraceEnabled()) {
        log.trace(">signRequest: usepreviouskey=" + usepreviouskey + ", createlinkcert=" + createlinkcert);
    }
    byte[] ret = request;
    try {
        CardVerifiableCertificate cacert = (CardVerifiableCertificate) getCACertificate();
        if (cacert == null) {
            // if we don't have a CA certificate, we can't sign any request, just return it
            return request;
        }
        CATokenContainer catoken = getCAToken();
        // Get either the current or the previous signing key for signing this request
        int key = SecConst.CAKEYPURPOSE_CERTSIGN;
        if (usepreviouskey) {
            log.debug("Using previous CertSign key to sign request");
            key = SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS;
        } else {
            log.debug("Using current CertSign key to sign request");
        }
        KeyPair keyPair = new KeyPair(catoken.getPublicKey(key), catoken.getPrivateKey(key));
        String signAlg = getCAToken().getCATokenInfo().getSignatureAlgorithm();
        // Create the CA reference, should be from signing certificates holder field
        HolderReferenceField caHolder = cacert.getCVCertificate().getCertificateBody().getHolderReference();
        String sequence = caHolder.getSequence();
        // See if we have a previous sequence to put in the CA reference instead of the same as we have from the request
        String propdata = catoken.getCATokenInfo().getProperties();
        Properties prop = new Properties();
        if (propdata != null) {
            prop.load(new ByteArrayInputStream(propdata.getBytes()));
        }
        String previousSequence = (String) prop.get(ICAToken.PREVIOUS_SEQUENCE_PROPERTY);
        // Only use previous sequence if we also use previous key
        if ((previousSequence != null) && (usepreviouskey)) {
            sequence = previousSequence;
            log.debug("Using previous sequence in caRef: " + sequence);
        } else {
            log.debug("Using current sequence in caRef: " + sequence);
        }
        // Set the CA reference field for the authentication signature
        CAReferenceField caRef = new CAReferenceField(caHolder.getCountry(), caHolder.getMnemonic(), sequence);

        CVCertificate cvcert = null;
        try {
            byte[] binbytes = request;
            try {
                // We don't know if this is a PEM or binary certificate or request request so we first try to 
                // decode it as a PEM certificate, and if it's not we try it as a PEM request and finally as a binary request 
                Collection<Certificate> col = CertTools.getCertsFromPEM(new ByteArrayInputStream(request));
                Certificate cert = col.iterator().next();
                if (cert != null) {
                    binbytes = cert.getEncoded();
                }
            } catch (Exception e) {
                log.debug("This is not a PEM certificate?: " + e.getMessage());
                try {
                    binbytes = RequestMessageUtils.getRequestBytes(request);
                } catch (Exception e2) {
                    log.debug("This is not a PEM request?: " + e2.getMessage());
                }
            }
            // This can be either a CV certificate, a CV certificate request, or an authenticated request that we should re-sign
            CVCObject parsedObject;
            parsedObject = CertificateParser.parseCVCObject(binbytes);
            if (parsedObject instanceof CVCertificate) {
                cvcert = (CVCertificate) parsedObject;
                log.debug("This is a reqular CV request, or cert.");
            } else if (parsedObject instanceof CVCAuthenticatedRequest) {
                CVCAuthenticatedRequest authreq = (CVCAuthenticatedRequest) parsedObject;
                cvcert = authreq.getRequest();
                log.debug(
                        "This is an authenticated CV request, we will overwrite the old authentication with a new.");
            }
        } catch (ParseException e) {
            String msg = intres.getLocalizedMessage("cvc.error.notcvcrequest");
            log.info(msg, e);
            return request;
        } catch (ClassCastException e) {
            String msg = intres.getLocalizedMessage("cvc.error.notcvcrequest");
            log.info(msg, e);
            return request;
        }
        // Check if the input was a CVCA certificate, which is the same CVCA as this. If all is true we should create a CVCA link certificate
        // instead of an authenticated request
        CardVerifiableCertificate cvccert = new CardVerifiableCertificate(cvcert);
        HolderReferenceField cvccertholder = cvccert.getCVCertificate().getCertificateBody()
                .getHolderReference();
        AuthorizationRoleEnum authRole = null;
        AccessRightEnum rights = null;
        try {
            authRole = cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate()
                    .getAuthorizationField().getRole();
            rights = cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate()
                    .getAuthorizationField().getAccessRight();
        } catch (NoSuchFieldException e) {
            log.debug(
                    "No AuthorizationRoleEnum or AccessRightEnum, this is not a CV certificate so we can't make a link certificate: "
                            + e.getMessage());

        }
        if (createlinkcert && (authRole != null) && (rights != null)) {
            log.debug("We will create a link certificate.");
            String msg = intres.getLocalizedMessage("cvc.info.createlinkcert", cvccertholder.getConcatenated(),
                    caRef.getConcatenated());
            log.info(msg);
            PublicKey pk = cvccert.getPublicKey();
            Date validFrom = cvccert.getCVCertificate().getCertificateBody().getValidFrom();
            Date validTo = cvccert.getCVCertificate().getCertificateBody().getValidTo();
            // Generate a new certificate with the same contents as the passed in certificate, but with new caRef and signature
            CVCertificate retcert = CertificateGenerator.createCertificate(pk, keyPair.getPrivate(), signAlg,
                    caRef, cvccertholder, authRole, rights, validFrom, validTo, catoken.getProvider());
            ret = retcert.getDEREncoded();
            log.debug("Signed a CardVerifiableCertificate CardVerifiableCertificate.");
        } else {
            log.debug("Creating authenticated request with signature alg: " + signAlg + ", using provider "
                    + catoken.getProvider());
            CVCAuthenticatedRequest authreq = CertificateGenerator.createAuthenticatedRequest(cvcert, keyPair,
                    signAlg, caRef, catoken.getProvider());
            ret = authreq.getDEREncoded();
            log.debug("Signed a CardVerifiableCertificate request and returned a CVCAuthenticatedRequest.");
        }
    } catch (IllegalKeyStoreException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchProviderException e) {
        throw new RuntimeException(e);
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ConstructionException e) {
        throw new RuntimeException(e);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<signRequest");
    }
    return ret;
}

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

public CrmfRAPbeRequestTest(String arg0) throws CertificateException {
    super(arg0);//  www.j  a  va 2 s .c o  m
    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();
    // Configure CMP for this test
    updatePropertyOnServer(CmpConfiguration.CONFIG_OPERATIONMODE, "ra");
    updatePropertyOnServer(CmpConfiguration.CONFIG_ALLOWRAVERIFYPOPO, "true");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RESPONSEPROTECTION, "pbe");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_AUTHENTICATIONSECRET, PBEPASSWORD);
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_CERTIFICATEPROFILE, CPNAME);
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_ENDENTITYPROFILE, EEPNAME);
    updatePropertyOnServer(CmpConfiguration.CONFIG_RACANAME, cainfo.getName());
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONMODULE, CmpConfiguration.AUTHMODULE_HMAC);
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONPARAMETERS, "-");
    // Configure a Certificate profile (CmpRA) using ENDUSER as template and
    // check "Allow validity override".
    if (certificateProfileSession.getCertificateProfile(admin, CPNAME) == null) {
        CertificateProfile cp = new EndUserCertificateProfile();
        cp.setAllowValidityOverride(true);
        try { // TODO: Fix this better
            certificateProfileSession.addCertificateProfile(admin, CPNAME, cp);
        } catch (CertificateProfileExistsException e) {
            e.printStackTrace();
        }
    }
    int cpId = certificateProfileSession.getCertificateProfileId(admin, CPNAME);
    if (endEntityProfileSession.getEndEntityProfile(admin, EEPNAME) == null) {
        // Configure an EndEntity profile (CmpRA) with allow CN, O, C in DN
        // and rfc822Name (uncheck 'Use entity e-mail field' and check
        // 'Modifyable'), MS UPN in altNames in the end entity profile.
        EndEntityProfile eep = new EndEntityProfile(true);
        eep.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, "" + cpId);
        eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId);
        eep.setModifyable(DnComponents.RFC822NAME, 0, true);
        eep.setUse(DnComponents.RFC822NAME, 0, false); // Don't use field
        // from "email" data
        try {
            endEntityProfileSession.addEndEntityProfile(admin, EEPNAME, eep);
        } catch (EndEntityProfileExistsException e) {
            log.error("Could not create end entity profile.", e);
        }
    }
}

From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java

String generateFingerPrint(Certificate cert) {

    final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    StringBuilder buffer = new StringBuilder(60);
    try {/*from  w  w  w  . j  ava  2 s .  c o  m*/

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] data = md.digest(cert.getEncoded());

        for (int i = 0; i < data.length; i++) {
            if (buffer.length() > 0) {
                buffer.append(":");
            }

            buffer.append(HEX[(0xF0 & data[i]) >>> 4]);
            buffer.append(HEX[0x0F & data[i]]);
        }

    } catch (CertificateEncodingException e) {
        throw new InvalidParameterValueException("Bad certificate encoding");
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidParameterValueException("Bad certificate algorithm");
    }

    return buffer.toString();
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java

/**
 * Test importing a new certificate chain to an existing keystore.
 * @throws Exception //from w w  w. j  av  a2  s.co m
 */
public void testImportCertificateChain() throws Exception {
    LOG.info("testImportCertificateChain");

    final boolean autoActivate = false;

    final int workerId = WORKER_CMS;
    try {
        setCMSSignerPropertiesCombined(workerId, autoActivate);

        // Generate key and issue certificate
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
        kpg.initialize(1024);
        final KeyPair keyPair = kpg.generateKeyPair();

        // Create a key-pair and certificate in the keystore
        FileOutputStream out = null;
        try {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null, null);

            final X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=Test", (long) 30 * 24 * 60 * 60 * 365, keyPair);
            ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain);

            out = new FileOutputStream(keystoreFile);
            ks.store(out, pin.toCharArray());
        } finally {
            IOUtils.closeQuietly(out);
        }

        workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11");
        workerSession.reloadConfiguration(workerId);

        // Activate first so we can generate a key
        workerSession.activateSigner(workerId, pin);

        List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
        assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty());

        // generate a new certificate
        final X509Certificate newCert = getSelfCertificate("CN=TestNew", (long) 30 * 24 * 60 * 60 * 365,
                keyPair);

        workerSession.importCertificateChain(workerId, Arrays.asList(newCert.getEncoded()), "newkey11", null);

        final Certificate readCert = workerSession.getSignerCertificate(workerId);
        assertTrue("Matching certificates", Arrays.equals(newCert.getEncoded(), readCert.getEncoded()));
    } finally {
        FileUtils.deleteQuietly(keystoreFile);
        removeWorker(workerId);
    }
}

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

public CrmfRARequestTest(String arg0) throws CertificateEncodingException, CertificateException {
    super(arg0);/*  w ww. j  av  a 2s . c  om*/

    admin = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER);
    // Configure CMP for this test, we allow custom certificate serial numbers
    CertificateProfile profile = new EndUserCertificateProfile();
    try {
        certProfileSession.addCertificateProfile(admin, "CMPTESTPROFILE", profile);
    } catch (CertificateProfileExistsException e) {
        log.error("Could not create certificate profile.", e);
    }
    int cpId = certProfileSession.getCertificateProfileId(admin, "CMPTESTPROFILE");
    EndEntityProfile eep = new EndEntityProfile(true);
    eep.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, "" + cpId);
    eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId);
    eep.addField(DnComponents.COMMONNAME);
    eep.addField(DnComponents.ORGANIZATION);
    eep.addField(DnComponents.COUNTRY);
    eep.addField(DnComponents.RFC822NAME);
    eep.addField(DnComponents.UPN);
    eep.setModifyable(DnComponents.RFC822NAME, 0, true);
    eep.setUse(DnComponents.RFC822NAME, 0, false); // Don't use field from "email" data
    try {
        eeProfileSession.addEndEntityProfile(admin, "CMPTESTPROFILE", eep);
    } catch (EndEntityProfileExistsException e) {
        log.error("Could not create end entity profile.", e);
    }
    // Configure CMP for this test
    updatePropertyOnServer(CmpConfiguration.CONFIG_OPERATIONMODE, "ra");
    updatePropertyOnServer(CmpConfiguration.CONFIG_ALLOWRAVERIFYPOPO, "true");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RESPONSEPROTECTION, "signature");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_AUTHENTICATIONSECRET, PBEPASSWORD);
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_ENDENTITYPROFILE, "CMPTESTPROFILE");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_CERTIFICATEPROFILE, "CMPTESTPROFILE");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RACANAME, "AdminCA1");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_NAMEGENERATIONSCHEME, "DN");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_NAMEGENERATIONPARAMS, "CN");
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONMODULE, CmpConfiguration.AUTHMODULE_HMAC);
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONPARAMETERS, "-");

    CryptoProviderTools.installBCProvider();
    // Try to use AdminCA1 if it exists
    final CAInfo adminca1;

    adminca1 = caAdminSessionRemote.getCAInfo(admin, "AdminCA1");

    if (adminca1 == null) {
        final Collection<Integer> caids;

        caids = caSession.getAvailableCAs(admin);

        final Iterator<Integer> iter = caids.iterator();
        int tmp = 0;
        while (iter.hasNext()) {
            tmp = iter.next().intValue();
        }
        caid = tmp;
    } else {
        caid = adminca1.getCAId();
    }
    if (caid == 0) {
        assertTrue("No active CA! Must have at least one active CA to run tests!", false);
    }
    final CAInfo cainfo;

    cainfo = caAdminSessionRemote.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
            try {
                cacert = (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
            } catch (Exception e) {
                throw new Error(e);
            }
        } else {
            cacert = null;
        }
    } else {
        log.error("NO CACERT for caid " + caid);
        cacert = null;
    }
    issuerDN = cacert != null ? cacert.getIssuerDN().getName() : "CN=AdminCA1,O=EJBCA Sample,C=SE";
}

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

/** Sends a certificate for download to a client */
private void sendEndEntityCert(final AuthenticationToken administrator, HttpServletRequest req,
        HttpServletResponse res, String format, Certificate certcert)
        throws CertificateEncodingException, NoSuchFieldException, IOException, CADoesntExistsException,
        SignRequestSignatureException, AuthorizationDeniedException {
    byte[] cert = certcert.getEncoded();
    String ending;/*from  w ww .j a v  a2s .  c  o m*/
    if (certcert instanceof CardVerifiableCertificate) {
        ending = ".cvcert";
    } else if (StringUtils.equals(format, "PEM") || StringUtils.equals(format, "chain")) {
        ending = ".pem";
    } else if (StringUtils.equals(format, "PKCS7")) {
        ending = ".p7b";
    } else {
        ending = ".crt";
    }
    String filename = RequestHelper.getFileNameFromCertNoEnding(certcert, "ca");
    filename = filename + ending;
    // We must remove cache headers for IE
    ServletUtils.removeCacheHeaders(res);
    if ("netscape".equals(req.getParameter(INSTALLTOBROWSER_PROPERTY))) {
        res.setContentType("application/x-x509-user-cert");
    } else {
        res.setHeader("Content-disposition",
                "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
        res.setContentType("application/octet-stream");
    }
    if (StringUtils.equals(format, "PEM")) {
        RequestHelper.sendNewB64File(Base64.encode(cert, true), res, filename,
                RequestHelper.BEGIN_CERTIFICATE_WITH_NL, RequestHelper.END_CERTIFICATE_WITH_NL);
    } else if (StringUtils.equals(format, "PKCS7")) {
        byte[] pkcs7 = signSession.createPKCS7(administrator, certcert, true);
        RequestHelper.sendNewB64File(Base64.encode(pkcs7, true), res, filename,
                RequestHelper.BEGIN_PKCS7_WITH_NL, RequestHelper.END_PKCS7_WITH_NL);
    } else if (StringUtils.equals(format, "chain")) {
        int issuerCAId = CertTools.getIssuerDN(certcert).hashCode();
        LinkedList<Certificate> chain = new LinkedList<Certificate>(
                signSession.getCertificateChain(administrator, issuerCAId));
        chain.addFirst(certcert);
        byte[] chainbytes = CertTools.getPemFromCertificateChain(chain);
        RequestHelper.sendNewB64File(chainbytes, res, filename, "", ""); // chain includes begin/end already
    } else {
        res.setContentLength(cert.length);
        res.getOutputStream().write(cert);
    }
}

From source file:org.wso2.carbon.appmgt.gateway.token.AbstractJWTGenerator.java

/**
 * Helper method to get base 64 encoded thumb print for specific tenant.
 *
 * @param endUserName End user name//from  www.j a va 2  s  . c o  m
 * @param tenantId Tenant id
 * @return base 64 encoded thumb print
 * @throws AppManagementException on error while trying to get base 64 encoded thumb print
 */
private String getBase64EncodedThumbPrint(String endUserName, int tenantId) throws AppManagementException {
    try {
        String base64EncodedThumbPrint = base64EncodedThumbPrintMap.get(tenantId);
        if (base64EncodedThumbPrint == null) {
            //TODO: https://wso2.org/jira/browse/APPM-1061
            Certificate publicCert = getPublicCertificate(endUserName, tenantId);
            if (publicCert == null) {
                throw new AppManagementException("Public certificate is null for tenant " + tenantId);
            }
            MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
            byte[] der = publicCert.getEncoded();
            digestValue.update(der);
            byte[] digestInBytes = digestValue.digest();

            String publicCertThumbprint = bytesToHex(digestInBytes);
            base64EncodedThumbPrint = Base64Utils.encode(publicCertThumbprint.getBytes(StandardCharsets.UTF_8));
            if (base64EncodedThumbPrint != null) {
                base64EncodedThumbPrintMap.put(tenantId, base64EncodedThumbPrint);
            }
        }
        return base64EncodedThumbPrint;
    } catch (CertificateEncodingException e) {
        String error = "Error in generating public certificate thumbprint for tenant " + tenantId;
        throw new AppManagementException(error, e);
    } catch (NoSuchAlgorithmException e) {
        String error = "Signature algorithm " + signatureAlgorithm + " not found.";
        throw new AppManagementException(error, e);
    }
}