`
bruce008
  • 浏览: 172868 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

SSL cert

    博客分类:
  • J2EE
 
阅读更多

we use lots of ssh to access the web service or https. Sometime  to create the cerfication file named:

jssecacerts

Then we can just copy this file to  $java_home/lib/security

 

 

/**
 * http://blogs.sun.com/andreas/resource/InstallCert.java
 * Use:
 * java InstallCert hostname
 * Example:
 *% java InstallCert ecc.fedora.redhat.com
 */

import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Class used to add the server's certificate to the KeyStore
 * with your trusted certificates.
 */
public class InstallCert {

    public static void main(String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
            return;
        }

        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            char SEP = File.separatorChar;
            File dir = new File(System.getProperty("java.home") + SEP
                    + "lib" + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }
        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println
                    (" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
        String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }

        X509Certificate cert = chain[k];
        String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);

        OutputStream out = new FileOutputStream("jssecacerts");
        ks.store(out, passphrase);
        out.close();

        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out.println
                ("Added certificate to keystore 'jssecacerts' using alias '"
                        + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }

}

 

分享到:
评论

相关推荐

    vmware证书过期问题处理相关脚本

    1. **证书过期问题**:VMware产品(如vSphere、vCenter等)使用的SSL/TLS证书都有有效期,过期后需要更新以确保通信的安全性。未及时更新的证书可能会导致管理界面无法访问、ESXi主机失去连接等问题。 2. **...

    ssl cacert.pem

    SLL rtificate problem: unable to get local issuer certificate

    InstallCert

    标签"Java Mail SSL Cert 证书"进一步细化了主题,涵盖了以下几个关键点: 1. **Java Mail**:这是Java中用于处理邮件的API,提供了丰富的功能,如创建、发送、接收和管理邮件。 2. **SSL**:是一种用于加密网络通信...

    K8S集群ssl证书监控ssl-exporter资源清单文件及镜像文件

    例如,如果要监控本地文件系统的证书,可以设置环境变量`SSL_CERT_FILE`: ```yaml env: - name: SSL_CERT_FILE value: /etc/ssl/certs.pem ``` 在实际使用中,可能还需要自定义`ssl-exporter`的配置,例如添加...

    create_cert.zip_SSL DELPHI_delphi cert_ssl

    在这个场景中,"create_cert.zip_SSL DELPHI_delphi cert_ssl" 提示我们,这个压缩包包含了一种在Delphi环境中创建SSL证书的工具或教程。 `create_cert.exe` 可能是一个执行文件,用于生成SSL证书。在开发涉及HTTPS...

    composer的ssl证书cacert.pem

    composer ssl cacert.pem证书

    ssl-cert-check:SSL证书即将到期时发送通知

    ssl-cert-check是一个Bourne shell脚本,可用于报告SSL证书过期。 该脚本旨在从cron运行,并且可以通过nagios发送电子邮件警告或记录警报。 用法: $ ./ssl-cert-check Usage: ./ssl-cert-check [ -e email ...

    UniDAC 7.1.4

    Product Description Universal Data Access Components (UniDAC) is a library of components that provides direct access to most popular database servers from Delphi, Delphi for .NET and, C++Builder....

    Template_ssl_cert_info.zip

    "Template_ssl_cert_info.zip"是一个针对Zabbix用户的资源,它提供了监控SSL证书过期的模板。 该压缩包包含一个名为"Template_ssl_cert_info.xml"的文件,这通常是一个Zabbix模板文件,用于导入到Zabbix服务器中。...

    命令行http服务器http-server.zip

    e.g.: -P http://someurl.com-S or --ssl Enable https.-C or --cert Path to ssl cert file &#40;default: cert.pem&#41;.-K or --key Path to ssl key file &#40;default: key.pem&#41;.-r or --robots Provide a...

    check_ssl_cert:check_ssl_cert是一个外壳脚本(可以用作Nagios插件),用于检查X.509证书的CA和有效性

    check_ssl_cert 用于检查X.509证书的Shell脚本(可用作Nagios插件): 检查服务器是否正在运行并提供有效的证书 检查CA是否匹配给定的模式 检查有效性 用法 Usage: check_ssl_cert -H host [OPTIONS] Arguments: ...

    MySQL 使用 SSL 连接配置详解

    mysql -u username -p --ssl-ca=/path/to/ca-cert.pem --ssl-cert=/path/to/client-cert.pem --ssl-key=/path/to/client-key.pem -h hostname ``` 或者在连接字符串中指定这些参数,具体取决于你的应用。 在...

    cacert.pem文件

    cacert.pem文件

    ssl证书cacert

    curl ssl ca根证书文件

    https-ssl-cert-check-zabbix:用于在站点上检查TLSSSL证书的有效性和有效期的脚本。 可与Zabbix或独立使用

    `https-ssl-cert-check-zabbix` 是一个专为此目的设计的脚本,允许系统管理员有效地监控网站的TLSSSL证书状态。该脚本不仅能够与Zabbix集成,还支持独立运行,提供灵活的监控解决方案。 首先,我们来理解TLS...

    ssl_cert_generator:用于本地开发的SSL证书和根CA证书的生成器

    本地SSL证书生成器安装$ git clone https://github.com/zablik/ssl_cert_generator.git生成认证我们将创建本地证书颁发机构(CA)。 然后,我们为任何本地域创建SSL证书,并使用我们的CA证书对其进行签名。 我们在...

    action-check-domain:观看您域的SSL证书和注册日期到期

    域和SSL证书监视程序 观看您的域的SSL证书和注册日期到期。 输入项 url 要检查的站点域(使用协议)。 产出 ssl-expire-date ...- run : echo 'SSL cert has ${{ steps.check-domain.outputs.ssl-exp

    create-ssl-certificate创建自签名SSL证书的命令行工具

    在Web服务器上配置这些证书,例如在Apache或Nginx中,你需要将`cert.pem`作为SSL证书文件,`key.pem`作为私钥文件。配置示例: **Apache配置:** ```apacheconfig *:443&gt; ServerName your.domain.com SSLEngine ...

    MySQL 8.0开启SSL.docx

    `ssl-cert=/path/to/server.crt` `ssl-key=/path/to/server.key` 这里,我们需要将证书和密钥文件的路径正确地配置到 MySQL 配置文件中。 3. 重启 MySQL после配置完成,我们需要重启 MySQL,以使配置生效...

    cronusagent:代理会说 RESTful 并快速执行 PaaS 任务

    # Install agent in /var/cronus with default ssl cert and no password wget -qO- ' http://cronuspaas.github.io/downloads/install_agent ' | sudo dev=true bash # custom ssl cert and user:password for ...

Global site tag (gtag.js) - Google Analytics