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:com.zacwolf.commons.crypto._CRYPTOfactory.java

public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport,
        final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keystore);/*from  w w  w  . j ava2 s. c o  m*/
    final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0];
    final MyTrustManager tm = new MyTrustManager(dtm);
    context.init(null, new TrustManager[] { tm }, null);
    final SSLSocketFactory factory = context.getSocketFactory();
    final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println("Certificate for server " + sitehostname + " is already trusted");
    } catch (SSLException e) {
        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.err.println("Could not obtain server certificate chain");
            return keystore;
        }
        System.out.println("Server sent " + chain.length + " certificate(s):");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            MessageDigest.getInstance("SHA1").update(cert.getEncoded());
            MessageDigest.getInstance("MD5").update(cert.getEncoded());
            final String alias = sitehostname + "-" + (i + 1);
            keystore.setCertificateEntry(alias, cert);
            System.out.println("Added certificate to keystore using alias '" + alias + "'");
        }
    }
    return keystore;
}

From source file:ee.ria.xroad.common.util.CryptoUtils.java

/**
 * Calculates a digest of the given certificate.
 * @param cert the certificate//from   w  ww  .j  av a2s. co  m
 * @return digest byte array of the certificate
 * @throws Exception if any errors occur
 */
public static byte[] certHash(X509Certificate cert) throws Exception {
    return certHash(cert.getEncoded());
}

From source file:ee.ria.xroad.common.util.CryptoUtils.java

/**
 * Calculates digest of the certificate and encodes it as lowercase hex.
 * @param cert the certificate/*w ww.  jav a2s . c o m*/
 * @return calculated certificate hex hash String
 * @throws Exception if any errors occur
 */
public static String calculateCertHexHash(X509Certificate cert) throws Exception {
    return hexDigest(DEFAULT_CERT_HASH_ALGORITHM_ID, cert.getEncoded());
}

From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java

/**
 * Get Certificate thumb print and Issuer Name from the ACS token.
 * @param acsToken the acs token/*  ww  w.jav a  2  s .co m*/
 * @return returnData the Map containing Thumb print and issuer name of X509Certiificate
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
public static Map<String, String> getCertificateThumbPrintAndIssuerName(String acsToken)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    byte[] acsTokenByteArray = null;
    Map<String, String> returnData = new HashMap<String, String>();

    try {
        acsTokenByteArray = acsToken.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder;
    String issuerName = null;
    StringBuffer thumbprint = null;

    try {
        docBuilder = builderFactory.newDocumentBuilder();
        Document resultDoc = docBuilder.parse(new ByteArrayInputStream(acsTokenByteArray));
        Element keyInfo = (Element) resultDoc.getDocumentElement()
                .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "KeyInfo").item(0);

        NodeList x509CertNodeList = keyInfo.getElementsByTagName("X509Certificate");
        Element x509CertNode = (Element) x509CertNodeList.item(0);
        if (x509CertNode == null) {
            return null;
        }
        //generating Certificate to retrieve its detail.
        String x509CertificateData = x509CertNode.getTextContent();
        InputStream inStream = new Base64InputStream(new ByteArrayInputStream(x509CertificateData.getBytes()));
        CertificateFactory x509CertificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) x509CertificateFactory
                .generateCertificate(inStream);
        String issuerDN = x509Certificate.getIssuerDN().toString();
        String[] issuerDNData = issuerDN.split("=");
        issuerName = issuerDNData[1];

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = x509Certificate.getEncoded();
        md.update(der);
        thumbprint = new StringBuffer();
        thumbprint.append(Hex.encodeHex(md.digest()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    returnData.put("IssuerName", issuerName);
    returnData.put("Thumbprint", thumbprint.toString().toUpperCase());
    return returnData;
}

From source file:eu.europa.ec.markt.dss.DSSUtils.java

/**
 * This method converts the given certificate into its PEM string.
 *
 * @param cert/*  www.  j  a v a 2  s  .  c  o  m*/
 * @return
 * @throws CertificateEncodingException
 */
public static String convertToPEM(final X509Certificate cert) throws CertificateEncodingException {

    final Base64 encoder = new Base64(64);

    final byte[] derCert = cert.getEncoded();
    final String pemCertPre = new String(encoder.encode(derCert));
    final String pemCert = CERT_BEGIN + pemCertPre + CERT_END;
    return pemCert;
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * // w ww  . j av a2s  .  co  m
 * 
 * http://stackoverflow.com/questions/1270703/how-to-retrieve-compute-an-
 * x509-certificates-thumbprint-in-java
 * 
 * 
 * 
 * @param cert
 * @return a string of the certificate thumb print
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
public static String getThumbPrint(javax.security.cert.X509Certificate cert)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] der = null;
    der = cert.getEncoded();
    md.update(der);
    byte[] digest = md.digest();
    return hexify(digest);

}

From source file:ee.ria.xroad.common.util.CryptoUtils.java

/**
 * Creates a new certificate ID instance (using SHA-1 digest calculator)
 * for the specified subject certificate serial number
 * and issuer certificate.//  ww w.  ja va 2 s .  co  m
 * @param subjectSerialNumber the subject certificate serial number
 * @param issuer the issuer certificate
 * @return the certificate id
 * @throws Exception if the certificate if cannot be created
 */
public static CertificateID createCertId(BigInteger subjectSerialNumber, X509Certificate issuer)
        throws Exception {
    return new CertificateID(createDigestCalculator(SHA1_ID), new X509CertificateHolder(issuer.getEncoded()),
            subjectSerialNumber);
}

From source file:be.fedict.eid.applet.service.JSONServlet.java

private static JSONObject createCertJSONObject(X509Certificate certificate, SimpleDateFormat simpleDateFormat)
        throws CertificateEncodingException, IOException {
    JSONObject certJSONObject = new JSONObject();
    certJSONObject.put("subject", certificate.getSubjectX500Principal().toString());
    certJSONObject.put("issuer", certificate.getIssuerX500Principal().toString());
    certJSONObject.put("serialNumber", certificate.getSerialNumber().toString());
    certJSONObject.put("notBefore", certificate.getNotBefore().toString());
    certJSONObject.put("notAfter", certificate.getNotAfter().toString());
    certJSONObject.put("signatureAlgo", certificate.getSigAlgName());
    certJSONObject.put("thumbprint", DigestUtils.shaHex(certificate.getEncoded()));
    certJSONObject.put("details", certificate.toString());
    certJSONObject.put("pem", toPem(certificate));

    return certJSONObject;
}

From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java

public static void checkReference(X509Certificate certificate,
        CompleteCertificateRefsType completeCertificateRefs) throws XAdESValidationException {
    byte[] encodedCert;
    try {/*from   w  w w.j a  v a  2 s. c  om*/
        encodedCert = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new XAdESValidationException("X509 encoding error: " + e.getMessage(), e);
    }
    CertIDListType certIDList = completeCertificateRefs.getCertRefs();
    if (null == certIDList) {
        throw new XAdESValidationException("missing CertRefs");
    }
    for (CertIDType certID : certIDList.getCert()) {
        DigestAlgAndValueType digestAlgAndValue = certID.getCertDigest();
        String xmlDigestAlgo = digestAlgAndValue.getDigestMethod().getAlgorithm();
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance(getDigestAlgo(xmlDigestAlgo));
        } catch (NoSuchAlgorithmException e) {
            throw new XAdESValidationException("message digest algo error: " + e.getMessage(), e);
        }
        byte[] expectedDigestValue = messageDigest.digest(encodedCert);
        byte[] refDigestValue = digestAlgAndValue.getDigestValue();
        if (Arrays.equals(expectedDigestValue, refDigestValue)) {
            return;
        }
    }
    throw new XAdESValidationException("X509 certificate not referenced");
}

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

/**
 * X.509 encode a certificate.//from  www.java2  s.  co  m
 *
 * @return The encoding
 * @param cert
 *            The certificate
 * @throws CryptoException
 *             If there was a problem encoding the certificate
 */
public static byte[] getCertEncodedX509(X509Certificate cert) throws CryptoException {
    try {
        return cert.getEncoded();
    } catch (CertificateException ex) {
        throw new CryptoException(res.getString("NoDerEncodeCertificate.exception.message"), ex);
    }
}