首页 > 其他分享 >ldaps 生成证书工具类

ldaps 生成证书工具类

时间:2023-11-21 14:44:30浏览次数:29  
标签:String chain 证书 System 生成 println new ldaps out

1.问题

修改用户名和密码需要用到ldaps,单纯的ldap389地址无法访问,必须通过636端口登陆后才能修改用户名密码,但是网上试过各种方法生成的证书都不能用,都是用keytool把证书加载到信任文件cacerts中,但是使用这个方法一直提示:

unable to find valid certification path to requested target executingh

后来无意中发现了一个工具类生成的文件可以使用,所以在此记录一下,免得以后碰到相同的问题.

2.代码:

package test;
import java.io.*;
import java.net.URL;
 
import java.security.*;
import java.security.cert.*;
 
import javax.net.ssl.*;
public class TestClass {

    public static void main(String[] args) throws Exception {
        String host = "10.2.37.8";
        int port = 636;
        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);
        }
    }
}


 

在启动参数输入地址:端口即可.

生成的文件放到jre的security路径下;

 

标签:String,chain,证书,System,生成,println,new,ldaps,out
From: https://www.cnblogs.com/lishuaiqi/p/17846551.html

相关文章

  • 企业级 SigningPDF 数字签名 - 如何安装 CFCA 全球信任文档签名证书
    派胜SigningPDF全球签是一款企业级PDF数字签名软件,可信数字签名、电子印章和时间戳解决方案。SigningPDF支持Adobe全球认可的证书颁发机构,高自动化为PDF文档添加可信合法的数字签名。访问SigningPDF官网下载最新版。https://www.paioffice.com/signingpdf/downloads如何......
  • crunch 生成字典
    生成4位验证码crunch44-d2%-t%%%%>crunch.out1、各种符号%代表数字@代表小写字母,代表大写字符^代表特殊符号2、选项-t指定输出格式 -t  %%%%  输出四位纯数字-d允许相同元素最多连续出现的次数-d  2% ......
  • Android studio使用javadoc生成 api 说明文档
    文章目录1、工具下载2、实用工具添加注释3、使用该工具生成api文档4、查看生成的api文档5、帮助1、工具下载2、实用工具添加注释官方wikiTogeneratejavadocsforactiveelementpress“shift+alt+G”.Togeneratejavadocsforallelementsincurrentjavafilepre......
  • Net 高级调试之十:轻量级代码生成的调试
    一、简介今天是《Net高级调试》的第十篇文章。说起来,高级调试,调试的内容还是挺多的,技巧也不少,但是,要想做一个合格的高级调试人员,还需要掌握如何调试动态生成的IL代码。今天要探讨的高级调试的技巧是如何调试通过Emit动态生成IL代码。可能有人会问,我们不是编写C#代......
  • nginx 启用SSL证书
    #usernobody;worker_processes1;#error_loglogs/error.log;#error_loglogs/error.lognotice;#error_loglogs/error.loginfo;#pidlogs/nginx.pid;events{worker_connections1024;}http{includemime.types;defau......
  • 在线微信wxid二维码生成器,转换微信号加好友工具接口,调用微信内部接口
    我声明一下,这个接口微信本身就存在的,并非是我逆向微信或者是HOOK微信,是正规的接口,任何人都能用,通过WXID直接添加对方好友,然后我就用易语言调用了一下接口而已,正规合规的哈,然后下面是框架和效果图以及完整代码。框架设计图:  下面是我示范的效果图,通过微信接口转换后转到名......
  • wxid转二维码在线生成器,加微信号好友接口工具,易语言源码分享
    用易语言开发的,我确保能用的,发布时间为11月20号,客户之前定制的我现在留着也没用,并且这个接口微信本身就有,我调用也不算是违规,然后下面是框架图和代码。框架图:  演示的图,通过WXID可以转到个人名片上面:【微信正规接口并非HOOK逆向】  易语言源码分享:=================......
  • openwrt uhttpd 配置 ssl 证书用于 dnspod 域名
    uHTTPd 是一个OpenWrt/LUCI开发者从头编写的Web服务器。它着力于实现一个稳定高效的服务器,能够满足嵌入式设备的轻量级任务需求,且能够与OpenWrt的配置框架(UCI)整合。默认情况下它被用于OpenWrt的Web管理接口 LuCI。当然,uHTTPd也能提供一个常规Web服务器所需要......
  • 禁止生成缩略图文件Thumbs.db
    如果在资源管理器的文件夹选项中设置「不显示缩略图」,可能仍会继续自动生成Thumbs.db文件。可以参考以下设置本地组策略的方法,实现使window不自动生成Thumbs.db文件。 ......
  • Oracle、达梦:生成32位字符串(ID)
    15、生成32位字符串达梦、oracle函数:sys_guid()、newid()转小写LOWER(char)selectrawtohex(sys_guid());--推荐使用newid()selectREPLACE(newid(),'-','');--转小写selectLOWER(REPLACE(newid(),'-',''));......