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.kse.crypto.x509.X509CertUtil.java

/**
 * Convert the supplied certificate object into an X509Certificate object.
 *
 * @param certIn//ww  w .  j a  v a2 s .c o  m
 *            The Certificate object
 * @return The converted X509Certificate object
 * @throws CryptoException
 *             A problem occurred during the conversion
 */
public static X509Certificate convertCertificate(Certificate certIn) throws CryptoException {
    try {
        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());
        ByteArrayInputStream bais = new ByteArrayInputStream(certIn.getEncoded());
        return (X509Certificate) cf.generateCertificate(bais);
    } catch (CertificateException | NoSuchProviderException e) {
        throw new CryptoException(res.getString("NoConvertCertificate.exception.message"), e);
    }
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Accepts an abstract {@link Certificate} and returns an {@link X509Certificate}. Because {@code sslSocket.getSession().getPeerCertificates()} returns an array of the
 * abstract certificates, they must be translated to X.509 to replace the functionality of {@code sslSocket.getSession().getPeerCertificateChain()}.
 *
 * @param abstractCertificate the {@code java.security.cert.Certificate}
 * @return a new {@code java.security.cert.X509Certificate}
 * @throws CertificateException if there is an error generating the new certificate
 *//* ww  w .j a  v  a2  s .com*/
public static X509Certificate convertAbstractX509Certificate(Certificate abstractCertificate)
        throws CertificateException {
    if (abstractCertificate == null || !(abstractCertificate instanceof X509Certificate)) {
        throw new IllegalArgumentException("The certificate cannot be null and must be an X.509 certificate");
    }

    try {
        return formX509Certificate(abstractCertificate.getEncoded());
    } catch (java.security.cert.CertificateEncodingException e) {
        throw new CertificateException(e);
    }
}

From source file:org.apache.nifi.security.util.CertificateUtils.java

/**
 * Accepts an abstract {@link java.security.cert.Certificate} and returns an {@link X509Certificate}. Because {@code sslSocket.getSession().getPeerCertificates()} returns an array of the
 * abstract certificates, they must be translated to X.509 to replace the functionality of {@code sslSocket.getSession().getPeerCertificateChain()}.
 *
 * @param abstractCertificate the {@code java.security.cert.Certificate}
 * @return a new {@code java.security.cert.X509Certificate}
 * @throws CertificateException if there is an error generating the new certificate
 *///from w w w  . ja v  a  2s. c  o  m
public static X509Certificate convertAbstractX509Certificate(java.security.cert.Certificate abstractCertificate)
        throws CertificateException {
    if (abstractCertificate == null || !(abstractCertificate instanceof X509Certificate)) {
        throw new IllegalArgumentException("The certificate cannot be null and must be an X.509 certificate");
    }

    try {
        return formX509Certificate(abstractCertificate.getEncoded());
    } catch (java.security.cert.CertificateEncodingException e) {
        throw new CertificateException(e);
    }
}

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

/**
 * Convert the supplied certificate object into an X509Certificate object.
 *
 * @param certIn/*from   ww w.  ja va 2  s .co m*/
 *            The Certificate object
 * @return The converted X509Certificate object
 * @throws CryptoException
 *             A problem occurred during the conversion
 */
public static X509Certificate convertCertificate(Certificate certIn) throws CryptoException {
    try {
        CertificateFactory 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:org.kuali.rice.ksb.security.AbstractDigitalSigner.java

protected String getEncodedCertificate(Certificate certificate) throws Exception {
    return new String(Base64.encodeBase64(certificate.getEncoded()), "UTF-8");
}

From source file:com.vmware.aurora.vc.vcservice.VcService.java

/**
 * Returns a PEM representation of a certificate
 *
 * @param cert A non-null certificate//from w  ww .j  a  v a 2 s.  c o  m
 * @return The PEM representation
 * @throws CertificateEncodingException, if certificate is malformed
 */
private static String CertificateToPem(Certificate cert) throws CertificateEncodingException {
    byte[] base64 = Base64.encodeBase64Chunked(cert.getEncoded());
    StringBuffer sb = new StringBuffer();
    sb.append("-----BEGIN CERTIFICATE-----\n");
    sb.append(new String(base64));
    sb.append("-----END CERTIFICATE-----");
    return sb.toString();
}

From source file:orca.shirako.container.RemoteRegistryCache.java

/**
 * Register an actor with the registry//ww  w . ja  v a 2 s  . c  om
 * @param actor actor
 */
public static void registerWithRegistry(IActor actor) {
    // External actor registry operations
    // If actor needs to be registered at external registry (i.e
    // PropertyRegistryUrl is set to the url for the registry),
    // register actor with external registry

    // NOTE: we register with local cache no matter what (if registry is specified or not)
    try {
        String act_name = actor.getName();
        String act_type = (new Integer(actor.getType())).toString();
        String act_guid = actor.getGuid().toString();
        String act_desc = actor.getDescription();

        String act_soapaxis2url = Globals.getContainer().getConfiguration()
                .getProperty(IOrcaConfiguration.PropertySoapAxis2Url);
        if (act_soapaxis2url != null) {
            act_soapaxis2url += "/services/" + actor.getName();
        } else {
            act_soapaxis2url = "None";
        }

        String act_class = actor.getClass().getCanonicalName();
        String act_mapper_class = actor.getPolicy().getClass().getCanonicalName();

        String act_pubkey = actor.getShirakoPlugin().getKeyStore().getActorCertificate().getPublicKey()
                .toString();
        if (act_pubkey == null) {
            act_pubkey = "None";
        }

        // get actor cert
        Certificate cert = actor.getShirakoPlugin().getKeyStore().getActorCertificate();
        byte[] bytes = null;

        try {
            bytes = cert.getEncoded();
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("Failed to encode the certificate");
        }

        String base64 = Base64.encodeBytes(bytes);
        //Globals.Log.info("Actor certificate in BASE64: \n" + base64);
        String act_cert64 = base64;

        // register with local cache regardless of whether external registry is used
        HashMap<String, String> res = new HashMap<String, String>();
        res.put(RemoteRegistryCache.ActorName, act_name);
        res.put(RemoteRegistryCache.ActorGuid, act_guid);
        String actor_type = null;

        if (act_type.equalsIgnoreCase("1")) {
            actor_type = OrcaConstants.SM;
        }
        if (act_type.equalsIgnoreCase("2")) {
            actor_type = OrcaConstants.BROKER;
        }
        if (act_type.equalsIgnoreCase("3")) {
            actor_type = OrcaConstants.SITE;
        }
        res.put(RemoteRegistryCache.ActorType, actor_type);
        res.put(RemoteRegistryCache.ActorLocation, act_soapaxis2url);
        res.put(RemoteRegistryCache.ActorProtocol, OrcaConstants.ProtocolSoapAxis2);
        res.put(RemoteRegistryCache.ActorCert64, act_cert64);
        RemoteRegistryCache.getInstance().addLocalCacheEntry(act_guid, res);

        // now try registering with remote
        String registryUrl = Globals.getContainer().getConfiguration()
                .getProperty(OrcaContainer.PropertyRegistryUrl);
        String registryMethod = Globals.getContainer().getConfiguration()
                .getProperty(OrcaContainer.PropertyRegistryMethod);
        if (registryUrl == null || registryMethod == null) {
            Globals.Log.info("No external registry is specified.");
            return;
        }

        Globals.Log.info(
                "Registering actor with external registry at " + registryUrl + " using " + registryMethod);

        Vector<String> params = new Vector<String>();
        // This order of insert is very important, because the xml-rpc
        // server expects the strings in this order
        params.addElement(act_name);
        params.addElement(act_type);
        params.addElement(act_guid);
        params.addElement(act_desc);
        params.addElement(act_soapaxis2url);
        params.addElement(act_class);
        params.addElement(act_mapper_class);
        params.addElement(act_pubkey);
        params.addElement(act_cert64);
        try {
            Globals.Log
                    .debug("Inserting into registry - Actor:" + act_name + " | Type:" + act_type + " | GUID: "
                            + act_guid + " | Description: " + act_desc + " | soapaxis2url: " + act_soapaxis2url
                            + " | ActorClass: " + act_class + " | ActorMapperClass: " + act_mapper_class);

            // add actor key and cert into the multikeymanager
            mkm.addPrivateKey(act_guid, actor.getShirakoPlugin().getKeyStore().getActorPrivateKey(),
                    actor.getShirakoPlugin().getKeyStore().getActorCertificate());

            // before we do SSL to registry, set our identity
            mkm.setCurrentGuid(act_guid);

            XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
            config.setServerURL(new URL(registryUrl + "/"));
            XmlRpcClient client = new XmlRpcClient();
            client.setConfig(config);

            HttpClient h = new HttpClient(connMgr);
            // set this transport factory for host-specific SSLContexts to work
            XmlRpcCommonsTransportFactory f = new XmlRpcCommonsTransportFactory(client);
            f.setHttpClient(h);
            client.setTransportFactory(f);

            String stat = (String) client.execute(registryMethod, params);
            Globals.Log.info("Registry returned: " + stat);
        } catch (Exception ex) {
            Globals.Log.error("Could not connect to the registry server " + registryUrl + ": ", ex);
        }
        // start update thread
        ActorLiveness checkActorLive = new ActorLiveness(actor.getGuid().toString(), registryUrl,
                registryMethod);
    } catch (Exception e) {
        Globals.Log.error("An error occurred whle attempting to register actor " + actor.getName()
                + " with external registry", e);
    }
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

/**
 * Calculates the hash of the certificate known as the "thumbprint"
 * and returns it as a string representation.
 *
 * @param cert The certificate to hash.//from w ww . ja  v a  2 s.  c o  m
 * @param algorithm The hash algorithm to use.
 * @return The SHA-1 hash of the certificate.
 * @throws CertificateException
 */
private static String getThumbprint(Certificate cert, String algorithm) throws CertificateException {
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException(e);
    }
    byte[] encodedCert = cert.getEncoded();
    StringBuilder sb = new StringBuilder(encodedCert.length * 2);
    Formatter f = new Formatter(sb);
    try {
        for (byte b : digest.digest(encodedCert))
            f.format("%02x", b);
    } finally {
        f.close();
    }
    return sb.toString();
}

From source file:com.thoughtworks.go.security.Registration.java

public String toJson() {
    Map<String, Object> ret = new HashMap<>();
    ret.put("agentPrivateKey", serialize("RSA PRIVATE KEY", privateKey.getEncoded()));
    StringBuilder builder = new StringBuilder();
    for (Certificate c : chain) {
        try {/*  w  ww .  java  2  s .co m*/
            builder.append(serialize("CERTIFICATE", c.getEncoded()));
        } catch (CertificateEncodingException e) {
            throw bomb(e);
        }
    }
    ret.put("agentCertificate", builder.toString());
    return new Gson().toJson(ret);
}

From source file:org.electrologic.convergence.server.NotaryBundleServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    try {/*from   w ww  . jav a2  s  .  co m*/
        super.init(config);
        ServletContext ctx = config.getServletContext();
        Sha1RSASignature signer = (Sha1RSASignature) ctx.getAttribute(TargetConfigurator.SIGNERPATH);
        Certificate cert = signer.getCertificate();
        // convert certificate to PEM format
        byte[] derCert = cert.getEncoded();
        String base64Cert = Base64.encodeToString(derCert, true);
        base64Cert = base64Cert.replace("\r", "");
        StringBuilder buf = new StringBuilder(10000);
        buf.append("-----BEGIN CERTIFICATE-----\n");
        buf.append(base64Cert);
        buf.append("\n-----END CERTIFICATE-----\n");

        pemCert = buf.toString();
    } catch (CertificateEncodingException ex) {
        String msg = "Failed to convert certificate to PEM format.";
        logger.error(msg, ex);
        throw new ServletException(msg, ex);
    }
}