Example usage for java.security.cert X509Certificate getEncoded

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

Introduction

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

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:org.codice.ddf.security.certificate.generator.PkiTools.java

/**
 * Given an X509 certificate, return a PEM encoded string representation of the certificate.
 *
 * @param cert certificate//w w  w.  ja va  2s  .c  o  m
 * @return PEM encoded String
 */
public static String certificateToPem(X509Certificate cert) {
    Validate.isTrue(cert != null, "Certificate cannot be null");
    try {
        return derToPem(cert.getEncoded());
    } catch (RuntimeException | CertificateEncodingException e) {
        throw new CertificateGeneratorException("Unable to convert the certificate to a PEM object", e);
    }
}

From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception {
    final URL url2 = new URL(url);
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(),
            url2.getPort() > 0 ? url2.getPort() : 443);
    socket.setSoTimeout(10000);// ww  w .  ja v a 2s .  c  om
    try {
        socket.startHandshake();
        socket.close();
    } catch (SSLException e) {
    }

    final X509Certificate[] chain = trustManager.chain;
    if (chain == null) {
        LOGGER.error("Could not obtain server certificate chain from: " + url);
        return;
    }

    final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    final MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate cert = chain[i];
        final String alias = url2.getHost() + "-" + (i + 1);
        if (!trustStore.containsAlias(alias)) {
            sha1.update(cert.getEncoded());
            md5.update(cert.getEncoded());
            LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN()
                    + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: "
                    + printHexBinary(md5.digest()) + ", Alias: " + alias);
            trustStore.setCertificateEntry(alias, cert);
        }
    }
}

From source file:cc.arduino.plugins.wifi101.flashers.java.NinaFlasher.java

protected static String convertToPem(X509Certificate cert) {
    Base64 encoder = new Base64(64, "\n".getBytes());
    String cert_begin = "-----BEGIN CERTIFICATE-----\n";
    String end_cert = "-----END CERTIFICATE-----";

    try {/*from w w w .  j  av  a2  s .  c o m*/
        byte[] derCert = cert.getEncoded();
        String pemCertPre = new String(encoder.encode(derCert));
        String pemCert = cert_begin + pemCertPre + end_cert;
        return pemCert;
    } catch (Exception e) {
        // do nothing
        return "";
    }
}

From source file:wptools.cmds.DumpCerts.java

private static void dumpCert(X509Certificate cert) {
    System.out.println("Serial No.: " + formatFing(cert.getSerialNumber().toByteArray()));
    try {//from   w  ww .  j a  v  a  2s  . c o m
        for (String ftype : FTYPES) {
            MessageDigest md = MessageDigest.getInstance(ftype);
            md.reset();
            System.out.format("%s: %s%n", ftype, formatFing(md.digest(cert.getEncoded())));
        }
    } catch (NoSuchAlgorithmException | CertificateException e) {
        Misc.die(e.getMessage());
    }
    System.out.println("Issued To: " + cert.getSubjectX500Principal());
    System.out.println("Issued By: " + cert.getIssuerX500Principal());
    System.out.format("Valid: from %tFT%<tT%<tz to %tFT%<tT%<tz%n%n", cert.getNotBefore(), cert.getNotAfter());
}

From source file:be.fedict.eidviewer.lib.X509Utilities.java

public static void certificateToDERFile(X509Certificate certificate, File file)
        throws CertificateEncodingException, IOException {
    FileOutputStream outputStream = null;
    try {/*from w w w.  j  av  a2 s. c o m*/
        outputStream = new FileOutputStream(file);
        outputStream.write(certificate.getEncoded());
    } finally {
        if (outputStream != null)
            outputStream.close();
    }
}

From source file:net.sf.keystore_explorer.crypto.signing.MidletSigner.java

/**
 * Sign a JAD file outputting the modified JAD to a different file.
 *
 * @param jadFile/* ww w . j  a v  a 2  s .com*/
 *            JAD file
 * @param outputJadFile
 *            Output JAD file
 * @param jarFile
 *            JAR file
 * @param privateKey
 *            Private RSA key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param certificateNumber
 *            Certificate number
 * @throws IOException
 *             If an I/O problem occurs while signing the MIDlet
 * @throws CryptoException
 *             If a crypto problem occurs while signing the MIDlet
 */
public static void sign(File jadFile, File outputJadFile, File jarFile, RSAPrivateKey privateKey,
        X509Certificate[] certificateChain, int certificateNumber) throws IOException, CryptoException {
    Properties jadProperties = readJadFile(jadFile);

    Properties newJadProperties = new Properties();

    // Copy over existing attrs (excepting digest and any certificates at
    // provided number)
    for (Enumeration enumPropNames = jadProperties.propertyNames(); enumPropNames.hasMoreElements();) {
        String propName = (String) enumPropNames.nextElement();

        // Ignore digest attr
        if (propName.equals(MIDLET_JAR_RSA_SHA1_ATTR)) {
            continue;
        }

        // Ignore certificates at provided number
        if (propName.startsWith(MessageFormat.format(SUB_MIDLET_CERTIFICATE_ATTR, certificateNumber))) {
            continue;
        }

        newJadProperties.put(propName, jadProperties.getProperty(propName));
    }

    // Get certificate attrs
    for (int i = 0; i < certificateChain.length; i++) {
        X509Certificate certificate = certificateChain[i];
        String base64Cert = null;
        try {
            base64Cert = new String(Base64.encode(certificate.getEncoded()));
        } catch (CertificateEncodingException ex) {
            throw new CryptoException(res.getString("Base64CertificateFailed.exception.message"), ex);
        }

        String midletCertificateAttr = MessageFormat.format(MIDLET_CERTIFICATE_ATTR, certificateNumber,
                (i + 1));
        newJadProperties.put(midletCertificateAttr, base64Cert);
    }

    // Get signed Base 64 SHA-1 digest of JAR file as attr
    byte[] signedJarDigest = signJarDigest(jarFile, privateKey);
    String base64SignedJarDigest = new String(Base64.encode(signedJarDigest));
    newJadProperties.put(MIDLET_JAR_RSA_SHA1_ATTR, base64SignedJarDigest);

    // Sort properties alphabetically
    TreeMap<String, String> sortedJadProperties = new TreeMap<String, String>();

    for (Enumeration names = newJadProperties.propertyNames(); names.hasMoreElements();) {
        String name = (String) names.nextElement();
        String value = newJadProperties.getProperty(name);

        sortedJadProperties.put(name, value);
    }

    // Write out new JAD properties to JAD file
    FileWriter fw = null;

    try {
        fw = new FileWriter(outputJadFile);

        for (Iterator itrSorted = sortedJadProperties.entrySet().iterator(); itrSorted.hasNext();) {
            Map.Entry property = (Map.Entry) itrSorted.next();

            fw.write(MessageFormat.format(JAD_ATTR_TEMPLATE, property.getKey(), property.getValue()));
            fw.write(CRLF);
        }
    } finally {
        IOUtils.closeQuietly(fw);
    }
}

From source file:org.kse.crypto.signing.MidletSigner.java

/**
 * Sign a JAD file outputting the modified JAD to a different file.
 *
 * @param jadFile/*from   w w w . j a  va2 s . co m*/
 *            JAD file
 * @param outputJadFile
 *            Output JAD file
 * @param jarFile
 *            JAR file
 * @param privateKey
 *            Private RSA key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param certificateNumber
 *            Certificate number
 * @throws IOException
 *             If an I/O problem occurs while signing the MIDlet
 * @throws CryptoException
 *             If a crypto problem occurs while signing the MIDlet
 */
public static void sign(File jadFile, File outputJadFile, File jarFile, RSAPrivateKey privateKey,
        X509Certificate[] certificateChain, int certificateNumber) throws IOException, CryptoException {
    Properties jadProperties = readJadFile(jadFile);

    Properties newJadProperties = new Properties();

    // Copy over existing attrs (excepting digest and any certificates at
    // provided number)
    for (Enumeration<?> enumPropNames = jadProperties.propertyNames(); enumPropNames.hasMoreElements();) {
        String propName = (String) enumPropNames.nextElement();

        // Ignore digest attr
        if (propName.equals(MIDLET_JAR_RSA_SHA1_ATTR)) {
            continue;
        }

        // Ignore certificates at provided number
        if (propName.startsWith(MessageFormat.format(SUB_MIDLET_CERTIFICATE_ATTR, certificateNumber))) {
            continue;
        }

        newJadProperties.put(propName, jadProperties.getProperty(propName));
    }

    // Get certificate attrs
    for (int i = 0; i < certificateChain.length; i++) {
        X509Certificate certificate = certificateChain[i];
        String base64Cert = null;
        try {
            base64Cert = new String(Base64.encode(certificate.getEncoded()));
        } catch (CertificateEncodingException ex) {
            throw new CryptoException(res.getString("Base64CertificateFailed.exception.message"), ex);
        }

        String midletCertificateAttr = MessageFormat.format(MIDLET_CERTIFICATE_ATTR, certificateNumber,
                (i + 1));
        newJadProperties.put(midletCertificateAttr, base64Cert);
    }

    // Get signed Base 64 SHA-1 digest of JAR file as attr
    byte[] signedJarDigest = signJarDigest(jarFile, privateKey);
    String base64SignedJarDigest = new String(Base64.encode(signedJarDigest));
    newJadProperties.put(MIDLET_JAR_RSA_SHA1_ATTR, base64SignedJarDigest);

    // Sort properties alphabetically
    TreeMap<String, String> sortedJadProperties = new TreeMap<String, String>();

    for (Enumeration<?> names = newJadProperties.propertyNames(); names.hasMoreElements();) {
        String name = (String) names.nextElement();
        String value = newJadProperties.getProperty(name);

        sortedJadProperties.put(name, value);
    }

    // Write out new JAD properties to JAD file
    FileWriter fw = null;

    try {
        fw = new FileWriter(outputJadFile);

        for (Iterator<Entry<String, String>> itrSorted = sortedJadProperties.entrySet().iterator(); itrSorted
                .hasNext();) {
            Entry<String, String> property = itrSorted.next();

            fw.write(MessageFormat.format(JAD_ATTR_TEMPLATE, property.getKey(), property.getValue()));
            fw.write(CRLF);
        }
    } finally {
        IOUtils.closeQuietly(fw);
    }
}

From source file:Main.java

/**
 * Generate the fingerprint for a dedicated type.
 * @param cert the certificate/*from  w  w w  . j  av a2s  .  c  o m*/
 * @param type the type
 * @return the fingerprint
 * @throws CertificateException
 */
private static byte[] generateFingerprint(X509Certificate cert, String type) throws CertificateException {
    final byte[] fingerprint;
    final MessageDigest md;
    try {
        md = MessageDigest.getInstance(type);
    } catch (Exception e) {
        // This really *really* shouldn't throw, as java should always have a SHA-256 and SHA-1 impl.
        throw new CertificateException(e);
    }

    fingerprint = md.digest(cert.getEncoded());

    return fingerprint;
}

From source file:org.tolven.gatekeeper.CertificateHelper.java

/**
 * Return the X509Certificate as a byte[] of the first alias in the keyStore
 * //from   ww w  .  j a  v  a2s  .com
 * @param keyStore
 * @return
 */
public static byte[] getX509CertificateByteArray(KeyStore keyStore) {
    X509Certificate x509Certificate = getX509Certificate(keyStore);
    try {
        return x509Certificate.getEncoded();
    } catch (CertificateEncodingException ex) {
        throw new RuntimeException("Could not get encoded bytes from X509Certificate", ex);
    }
}

From source file:wptools.lib.Misc.java

/**
 * Bypass the normal SSL certificate authentication. If the passed
 * fingerprint is null, bypasses all authentication (dangerous).
 * Else trust anything whose chain contains a cert with the specified
 * fingerprint./*from www  .ja  v a  2 s. c  o  m*/
 * @param fing      Fingerprint
 */
public static void bypassSslAuth(final byte[] fing) {
    // Determine fingerprint type from its length
    final String type;
    if (fing == null) {
        type = null;
    } else {
        switch (fing.length) {
        case MD5_LEN:
            type = "MD5";
            break;
        case SHA1_LEN:
            type = "SHA-1";
            break;
        case SHA256_LEN:
            type = "SHA-256";
            break;
        default:
            throw new IllegalArgumentException("Invalid hash.");
        }
    }

    // Create a trust manager
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            matchFing(certs);
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            matchFing(certs);
        }

        private void matchFing(X509Certificate[] certs) throws CertificateException {
            if (fing == null)
                return;
            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance(type);
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException(e);
            }
            for (X509Certificate cert : certs) {
                md.reset();
                if (Arrays.equals(md.digest(cert.getEncoded()), fing))
                    return;
            }
            throw new CertificateException("No matching fingerprint found.");
        }
    } };

    // Install the trust manager
    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };

    try {
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}