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.apache.hadoop.gateway.services.security.impl.X509CertificateUtil.java

public static void writeCertificateToFile(Certificate cert, final File file)
        throws CertificateEncodingException, IOException {
    byte[] bytes = cert.getEncoded();
    Base64 encoder = new Base64(76, "\n".getBytes("ASCII"));
    try (final FileOutputStream out = new FileOutputStream(file)) {
        out.write("-----BEGIN CERTIFICATE-----\n".getBytes("ASCII"));
        out.write(encoder.encodeToString(bytes).getBytes("ASCII"));
        out.write("-----END CERTIFICATE-----\n".getBytes("ASCII"));
    }//  w  w  w  . j  av  a2  s  . c om
}

From source file:be.fedict.eid.dss.protocol.simple.client.SignatureRequestUtil.java

/**
 * Constructs a DSS Simple Protocol service signature.
 * <p/>//w w  w. j  ava 2s . c om
 * If no spIdentity is specified returns <code>null</code>
 * 
 * @param spIdentity
 *            the SP Identity used for signing.
 * @param signatureRequest
 *            signature request, if <code>null</code> signatureRequestId
 *            needs to be specified.
 * @param signatureRequestId
 *            signature request ID, if <code>null</code>, signatureRequest
 *            needs to be specified
 * @param target
 *            required target
 * @param language
 *            optional language param
 * @param contentType
 *            optional document content type
 * @param relayState
 *            optional relay state
 * @return service signature DO containing the signature value, service
 *         signed property listing up all signed properties and the SP
 *         certificate chain.
 * @throws NoSuchAlgorithmException
 *             algorithm to sign/digest not found.
 * @throws InvalidKeyException
 *             signing key not valid
 * @throws SignatureException
 *             signature creation failure
 * @throws CertificateEncodingException
 *             certificate encoding failure
 */
public static ServiceSignatureDO getServiceSignature(

        KeyStore.PrivateKeyEntry spIdentity, String signatureRequest, String signatureRequestId, String target,
        String language, String contentType, String relayState)

        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateEncodingException {

    LOG.debug("get service signature");

    if (null == spIdentity) {
        LOG.warn("No SP Identity specified, no signature added.");
        return null;
    }
    if (null == signatureRequest && null == signatureRequestId) {
        throw new RuntimeException(
                "Either \"SignatureRequest\" or " + "\"SignatureRequestId\" needs to be provided.");
    }

    // construct service signature
    // TODO: configurable?
    Signature serviceSignature = Signature.getInstance("SHA1withRSA");
    serviceSignature.initSign(spIdentity.getPrivateKey());

    serviceSignature.update(target.getBytes());
    if (null != signatureRequest) {
        serviceSignature.update(signatureRequest.getBytes());
    } else {
        serviceSignature.update(signatureRequestId.getBytes());
    }
    if (null != language) {
        serviceSignature.update(language.getBytes());
    }
    if (null != contentType) {
        serviceSignature.update(contentType.getBytes());
    }
    if (null != relayState) {
        serviceSignature.update(relayState.getBytes());
    }

    byte[] serviceSignatureValue = serviceSignature.sign();

    String encodedServiceSignature = Base64.encodeBase64String(serviceSignatureValue);

    // construct service signed
    String serviceSigned = "target";
    if (null != signatureRequest) {
        serviceSigned += ",SignatureRequest";
    } else {
        serviceSigned += ",SignatureRequestId";
    }
    if (null != language) {
        serviceSigned += ",language";
    }
    if (null != contentType) {
        serviceSigned += ",ContentType";
    }
    if (null != relayState) {
        serviceSigned += ",RelayState";
    }

    // construct service certificate chain
    java.security.cert.Certificate[] serviceCertificateChain = spIdentity.getCertificateChain();
    String serviceCertificateChainSize = Integer.toString(serviceCertificateChain.length);

    List<String> serviceCertificates = new LinkedList<String>();
    for (java.security.cert.Certificate certificate : serviceCertificateChain) {
        String encodedServiceCertificate = Base64.encodeBase64String(certificate.getEncoded());
        serviceCertificates.add(encodedServiceCertificate);
    }

    return new ServiceSignatureDO(serviceSigned, encodedServiceSignature, serviceCertificateChainSize,
            serviceCertificates);
}

From source file:org.ambientdynamix.web.WebUtils.java

/**
 * xports an certificate to a file.//from w w w  . j a  va 2 s .co  m
 * 
 * @param cert
 *            The certificate to export.
 * @param file
 *            The destination file.
 * @param binary
 *            True if the cert should be written as a binary file; false to encode using Base64.
 */
public static void exportCertificate(java.security.cert.Certificate cert, File file, boolean binary) {
    Log.i(TAG, "Writing cert to: " + file.getAbsolutePath());
    try {
        // Get the encoded form which is suitable for exporting
        byte[] buf = cert.getEncoded();
        FileOutputStream os = new FileOutputStream(file);
        if (binary) {
            // Write in binary form
            os.write(buf);
        } else {
            // Write in text form
            Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
            wr.write("-----BEGIN CERTIFICATE-----\n");
            Base64.encodeBase64(buf);
            wr.write("\n-----END CERTIFICATE-----\n");
            wr.flush();
        }
        os.close();
    } catch (Exception e) {
        Log.w(TAG, "Error writing cert for " + file);
    }
}

From source file:org.gluu.oxtrust.ldap.service.SSLService.java

/**
 * Convert the supplied certificate object into an X509Certificate object.
 *
 * @param cert The Certificate object//from  w w  w  .  j a v  a 2s.c o  m
 * @return The converted X509Certificate object
 * @throws Exception A problem occurred during the conversion
 */
public static X509Certificate convertCertificate(Certificate cert) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, SECURITY_PROVIDER_BOUNCY_CASTLE);
    ByteArrayInputStream bais = new ByteArrayInputStream(cert.getEncoded());
    return (X509Certificate) cf.generateCertificate(bais);
}

From source file:com.vmware.identity.rest.core.util.CertificateHelper.java

/**
 * Generates the fingerprint of a certificate. The algorithm is as follows:
 * <ol>// www. j  a v  a  2 s  . c om
 *  <li>Apply 0xFF mask to remove byte's sign extension
 *  <li>Convert every byte to a hex number
 *  <li>Format every hex number as two characters
 *  <li>Put ':' delimiter between every two characters
 * </ol>
 *
 * @param certificate the certificate to generate a fingerprint of.
 * @return the fingerprint string of the certificate.
 * @throws CertificateEncodingException if an encoding error occurs.
 */
public static String generateFingerprint(Certificate certificate) throws CertificateEncodingException {
    MessageDigest digest;

    try {
        digest = MessageDigest.getInstance(FINGERPRINT_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("An error occurred while getting the message digest", e);
    }

    // Calculate SHA-1 hash
    byte[] hash = digest.digest(certificate.getEncoded());

    char delimiter = ':';
    int len = hash.length * 2 + hash.length - 1;

    StringBuilder fingerprint = new StringBuilder(len);

    for (int i = 0; i < hash.length; i++) {
        hash[i] &= 0xFF;

        fingerprint.append(String.format("%02x", hash[i]));

        if (i < hash.length - 1) {
            fingerprint.append(delimiter);
        }
    }

    return fingerprint.toString();
}

From source file:net.link.util.common.KeyUtils.java

public static void extractCertificate(PrivateKeyEntry privateKeyEntry, File certificateFile) {

    Certificate certificate = privateKeyEntry.getCertificate();
    try {//from  w  ww.  j av a 2  s. c  o  m
        FileUtils.writeByteArrayToFile(certificateFile, certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new InternalInconsistencyException("error encoding certificate ", e);
    } catch (IOException e) {
        throw new InternalInconsistencyException("error writing out certificate ", e);
    }
}

From source file:com.vmware.o11n.plugin.crypto.model.CryptoUtil.java

/**
 * PEM encode a certificate/*from   www .  j  a v a  2  s. co m*/
 *
 * @param pubKey Public
 * @return PEM encoded certificate string
 * @throws CertificateEncodingException
 */
public static String pemEncode(Certificate cert) throws CertificateEncodingException {
    String toReturn;
    if (cert instanceof X509Certificate) {
        final String certHeader = FIVE_DASH + "BEGIN CERTIFICATE" + FIVE_DASH;
        final String certFooter = FIVE_DASH + "END CERTIFICATE" + FIVE_DASH;
        Base64 encoder = new Base64(64);
        toReturn = String.join("\n", certHeader, new String(encoder.encode(cert.getEncoded())), certFooter);
    } else {
        throw new UnsupportedOperationException(
                "Unknown certificate type.  Only implemented for X509Certificate.");
    }
    return CryptoUtil.fixPemString(toReturn);
}

From source file:com.vmware.bdd.manager.SoftwareManagerCollector.java

/**
 * TODO this method has to be reverted:/*ww w.j a v a2 s  .c o m*/
 * because if the target path is not accessible, it will load cert from the default keystore in java home,
 * but still try to write it to the non accessible path.
 * @param certificate
 * @param keyStorePath
 */
protected static void saveSslCertificate(String certificate, String keyStorePath) {
    Certificate[] certs;
    //parse certificates
    try {
        if (CommonUtil.isBlank(certificate)) {
            throw SoftwareManagerCollectorException.BAD_CERT(null);
        }

        byte[] certBytes = Base64.decodeBase64(certificate.replaceAll("-----BEGIN CERTIFICATE-----", "")
                .replaceAll("-----END CERTIFICATE-----", "").getBytes());

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection c = cf.generateCertificates(new ByteArrayInputStream(certBytes));
        certs = new Certificate[c.toArray().length];

        if (c.size() == 0) {
            throw SoftwareManagerCollectorException.BAD_CERT(null);
        } else if (c.size() == 1) {
            certs[0] = cf.generateCertificate(new ByteArrayInputStream(certBytes));
        } else {
            certs = (Certificate[]) c.toArray(certs);
        }
    } catch (CertificateException e) {
        throw SoftwareManagerCollectorException.BAD_CERT(e);
    }

    //load & save keystore
    OutputStream out = null;
    try {
        KeyStore keyStore = CommonUtil.loadAppMgrKeyStore(keyStorePath);
        if (keyStore == null) {
            logger.error(Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE"));
            throw new SWMgrCollectorInternalException(
                    Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE"));
        }

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String md5Fingerprint = "";
        for (Certificate cert : certs) {
            md5.update(cert.getEncoded());
            md5Fingerprint = CommonUtil.toHexString(md5.digest());
            logger.debug("md5 finger print: " + md5Fingerprint);
            logger.debug("added cert: " + cert);
            keyStore.setCertificateEntry(md5Fingerprint, cert);
        }
        out = new FileOutputStream(keyStorePath + Constants.APPMANAGER_KEYSTORE_FILE);
        keyStore.store(new BufferedOutputStream(out), Constants.APPMANAGER_KEYSTORE_PASSWORD);
    } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) {
        logger.error(Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"), e);
        throw new SWMgrCollectorInternalException(e, Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"));
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.warn("Output stream of appmanagers.jks close failed.");
            }
        }
    }
}

From source file:org.bubblecloud.ilves.cache.UserClientCertificateCache.java

/**
 * Get user by certificate./*from   w w  w. ja v  a 2  s  .  c o m*/
 *
 * @param clientCertificate the client certificate
 * @param blackListNotFound whether certificate should be blacklisted if user is not found
 * @return the user or null if no matching user or more than one matching user was found.
 */
public static synchronized User getUserByCertificate(final Certificate clientCertificate,
        final boolean blackListNotFound) {
    if (blacklistCache.get(clientCertificate) != null) {
        LOGGER.debug(
                "Blacklisted TSL client certificate: " + ((X509Certificate) clientCertificate).getSubjectDN());
        return null;
    }
    final User cachedUser = certificateCache.get(clientCertificate);
    if (cachedUser != null) {
        LOGGER.debug("User matching TSL client certificate in cache: " + cachedUser.getUserId());
        return cachedUser;
    }
    final String encodedCertificateString;
    try {
        encodedCertificateString = Base64.encodeBase64String(clientCertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        LOGGER.error("Error encoding TSL client certificate for finding user from database.");
        return null;
    }

    final EntityManager entityManager = entityManagerFactory.createEntityManager();
    final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<User> criteria = criteriaBuilder.createQuery(User.class);
    final Root<User> root = criteria.from(User.class);
    criteria.where(criteriaBuilder.equal(root.get("certificate"), encodedCertificateString));
    final TypedQuery<User> query = entityManager.createQuery(criteria);
    final List<User> users = query.getResultList();
    if (users.size() == 1) {
        LOGGER.info("User found matching TSL client certificate: " + users.get(0).getUserId());
        certificateCache.put(clientCertificate, users.get(0));
        return users.get(0);
    } else if (users.size() > 1) {
        blacklistCache.put(clientCertificate, clientCertificate);
        LOGGER.error("Blacklisted TSL client certificate. More than one user had the certificate: "
                + clientCertificate);
        return null;
    } else {
        if (blackListNotFound) {
            blacklistCache.put(clientCertificate, clientCertificate);
            LOGGER.warn("Blacklisted TSL client certificate. User not found matching the certificate: "
                    + ((X509Certificate) clientCertificate).getSubjectDN());
        } else {
            LOGGER.warn("User not found matching the certificate: "
                    + ((X509Certificate) clientCertificate).getSubjectDN());
        }
        return null;
    }
}

From source file:com.vmware.identity.idm.server.ServerUtils.java

private static byte[] getCertBytes(Certificate cert) {
    byte[] bytes = null;

    try {/*from   ww  w .  j  a  v  a  2  s.  co m*/
        bytes = cert.getEncoded();
    } catch (CertificateEncodingException ex) {
        throw new RuntimeException("Failed to get certificate encoded bytes");
    }

    return bytes;
}