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.lizardirc.beancounter.security.FingerprintingSslSocketFactory.java

private void verify(SSLSocket socket) throws SSLException {
    SSLSession session = socket.getSession();
    Certificate cert = session.getPeerCertificates()[0];
    byte[] encoded;
    try {/*from w w  w .  j ava2  s  . c o m*/
        encoded = cert.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new SSLProtocolException("Invalid certificate encoding");
    }
    boolean match = Stream.<Function<byte[], String>>of(DigestUtils::md5Hex, DigestUtils::sha1Hex,
            DigestUtils::sha256Hex, DigestUtils::sha512Hex).map(f -> f.apply(encoded))
            .anyMatch(fingerprints::contains);

    if (!match) {
        System.err.println("Rejecting; fingerprint not matched");
        throw new SSLPeerUnverifiedException("Failed to verify: certificate fingerprint mismatch");
    }
}

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

private static CMPCertificate[] getCMPCert(Certificate cert) throws CertificateEncodingException, IOException {
    ASN1InputStream ins = new ASN1InputStream(cert.getEncoded());
    try {/* w w w .j  a va 2s  . co m*/
        ASN1Primitive pcert = ins.readObject();
        org.bouncycastle.asn1.x509.Certificate c = org.bouncycastle.asn1.x509.Certificate
                .getInstance(pcert.toASN1Primitive());
        CMPCertificate[] res = { new CMPCertificate(c) };
        return res;
    } finally {
        ins.close();
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

public static X509Certificate convertCertificate(Certificate certIn, String keyStoreType)
        throws CryptoException {
    try {//from ww  w. jav  a2s .  c o m
        CertificateFactory cf = null;
        if (keyStoreType.equals("HTKS")) {
            cf = CertificateFactory.getInstance(X509_CERT_TYPE, "GNU-PKI");
        } else {
            cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(certIn.getEncoded());
        return (X509Certificate) cf.generateCertificate(bais);
    } catch (CertificateException e) {
        throw new CryptoException(res.getString("NoConvertCertificate.exception.message"), e);
    } catch (NoSuchProviderException e) {
        throw new CryptoException(res.getString("NoConvertCertificate.exception.message"), e);
    }
}

From source file:com.adaptris.security.certificate.X509Handler.java

/**
 * Constructor using a pre-existing Certificate object .
 *
 * @param c the Certificate/*from   ww w.j a  va2s. c  om*/
 * @throws CertificateException if an error was encountered during the parse of the certificate
 * @throws IOException if there was an error reading the cert
 */
X509Handler(Certificate c) throws CertificateException, IOException {
    this(c.getEncoded());
}

From source file:se.curity.examples.oauth.jwt.JwtWithCertTest.java

/**
 * Load the private Keymap with the x5t256 thumbprint and the public key
 * The map only contains a single key//from ww w . j a v a2s .c om
 * @return
 * @throws Exception
 */
private Map<String, RSAPublicKey> prepareKeyMap() throws Exception {
    Map<String, RSAPublicKey> keys = new HashMap<>();

    Certificate cert = getCertificate();

    RSAPublicKey key = (RSAPublicKey) cert.getPublicKey();

    byte[] x5tS256 = DigestUtils.sha256(cert.getEncoded());
    String b64x5tS256 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(x5tS256);

    keys.put(b64x5tS256, key);

    return keys;
}

From source file:org.asimba.wa.integrationtest.util.SignatureHelper.java

public String getPEMEncodedCertificateFromKeystore() {
    Certificate certificate = getCertificateFromKeystore();
    Base64 encoder = new Base64(64);

    byte[] derCert;
    try {// w  w w. ja v  a2 s  .c om
        derCert = certificate.getEncoded();
        return new String(encoder.encode(derCert));
    } catch (CertificateEncodingException e) {
        _logger.error("Exception: {}", e.getMessage(), e);
        return "NO-CERT";
    }
}

From source file:org.openremote.controller.rest.FindCertificateByID.java

protected String getChain(String username) throws Exception {
    username = URLDecoder.decode(username, "UTF-8");
    String rootCAPath = configurationService.getItem("ca_path");
    String keystore = rootCAPath + "/server.jks";

    StringBuffer sb = new StringBuffer();
    sb.append(Constants.STATUS_XML_HEADER);

    sb.append("\n<chain>\n<server>\n");

    try {//from  w  ww. j av  a  2s . co  m
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keystore), "password".toCharArray());
        Certificate certificate = ks.getCertificate(CA_ALIAS);
        sb.append(new String(Base64.encodeBase64(certificate.getEncoded())));
    } catch (KeyStoreException e) {
        logger.error(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage());
    } catch (CertificateException e) {
        logger.error(e.getMessage());
    }

    sb.append("</server>\n<client>\n");

    try {
        Certificate certificate = clientService.getClientCertificate(username);
        if (certificate != null) {
            // Check client certificate
            //if(clientService.(dn, datum)
            X509Certificate x509cert = (X509Certificate) certificate;
            Principal dname = x509cert.getSubjectDN();
            Date notAfterDate = x509cert.getNotAfter();

            if (clientService.isClientValid(dname.toString())) {
                if (clientService.isClientDateValid(notAfterDate)) {
                    sb.append(new String(Base64.encodeBase64(certificate.getEncoded())));
                } else {
                    throw new Exception(ERROR_DATE_EXPIRED);
                }
            } else {
                throw new Exception(ERROR_INVALID_DN);
            }
        } else {
            logger.error("Client certificate is not found/null.");
        }
    } catch (CertificateEncodingException e) {
        logger.error(e.getMessage());
    }

    sb.append("</client>\n</chain>");
    sb.append(Constants.STATUS_XML_TAIL);

    return sb.toString();
}

From source file:mx.bigdata.cfdi.CFDv3.java

public void sign(PrivateKey key, Certificate cert) throws Exception {
    String signature = getSignature(key);
    document.setSello(signature);/*from   w  w  w.ja va  2  s  . c  o  m*/
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
}

From source file:eu.europa.esig.dss.x509.KeyStoreCertificateSource.java

public List<CertificateToken> getCertificatesFromKeyStore() {
    List<CertificateToken> list = new ArrayList<CertificateToken>();

    KeyStore keyStore = getKeyStore();
    try {/*from   www . ja  va  2s.c om*/
        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                Certificate certificate = keyStore.getCertificate(alias);
                CertificateToken certificateToken = DSSUtils.loadCertificate(certificate.getEncoded());
                list.add(certificateToken);
            }
        }
    } catch (Exception e) {
        logger.error("Unable to retrieve certificates from the keystore : " + e.getMessage(), e);
    }
    return list;
}

From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java

/**
 * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the
 * store with the password using {@link KeyStore#load(InputStream,
 * char[])} method./*from  w ww.j av a 2 s . c  o  m*/
 *
 * @param store The key store holding the certificate details
 * @param alias The alias of the certificate to use
 */
public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(store);

    // Loading the CA certificate from store.
    final Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    AsyncHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Embedded SSL certificate has expired.");
    }

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid.");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid.");
            } else {
                Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates.");
                try {
                    for (X509Certificate cert : chain) {
                        Log.i(LOG_TAG, "Server Certificate Details:");
                        Log.i(LOG_TAG, "---------------------------");
                        Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                        Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                        Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                        Log.i(LOG_TAG, "Version: " + cert.getVersion());
                        Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                        Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                        Log.i(LOG_TAG, "---------------------------");

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's public key chain.
                        cert.verify(rootca.getPublicKey());
                    }
                } catch (InvalidKeyException e) {
                    error = e;
                } catch (NoSuchAlgorithmException e) {
                    error = e;
                } catch (NoSuchProviderException e) {
                    error = e;
                } catch (SignatureException e) {
                    error = e;
                }
            }
            if (null != error) {
                Log.e(LOG_TAG, "Certificate error", error);
                throw new CertificateException(error);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return acceptedIssuers;
        }
    } }, null);

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}