JAVA:提取服务器证书 [英] JAVA: Extract Server Certificates

查看:230
本文介绍了JAVA:提取服务器证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助以获取适合的代码以获取服务器证书-有效和无效,由CA签名和自签名.任何链接和参考将不胜感激.

I want help in getting the apt piece of code to get server certificates - valid and invalid , signed by CA and self signed. Any links and references will be highly appreciated.

我有一个UNIX命令,该命令可以提供所需的信息,但我希望使用Java获得相同的输出. UNIX中的命令是这样的-

I have a UNIX command which gives me what i want but I want the same output using Java. The command in UNIX is like this -

echo -n | openssl s_client -connect www.gmail.com:443 -showcerts | sed -ne'/-BEGIN证书-/,/-END证书-/p'>/tmp/$SERVERNAME.cert

echo -n | openssl s_client -connect www.gmail.com:443 -showcerts | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert

这将返回gmail上的(不知道加密)证书链.我希望我的java程序提供完全相同的信息.打印整个证书链.

This returns the (dont know the encryption) chain of certificates on gmail. I want my java program to give the exact same information. Print the whole chain of certificates.

推荐答案

可以使用以下步骤完成此操作:

This can be done using the following steps:

  • 使用信任任何内容的TrustManager初始化SSLContext(此用例是使用这种信任管理器的少数原因之一).仅当您怀疑远程证书不受信任时.
  • 从中获取一个SSLSocketFactory.
  • 使用要连接的主机名在此工厂中创建一个SSLSocket.如果使用主机名(而不是InetAddress),则将在Java 7上启用SNI,因此等同于将-servername用作openssl命令的附加选项.
  • 开始握手(例如,使用startHandhsake())
  • 从此SSLSocket获取SSLSession.
  • 对于getPeerCertificates()中的每个Certificate:
    • 使用getEncoded()
    • 获取其编码值(作为byte[])
    • 将其转换为PEM,或者:
      • 使用BouncyCastle的PEMWriter.
      • 使用Base 64编码器(例如Apache Commons),添加BEGIN/END分隔符,并每64个字符用新行分隔字符串.
      • Initialise an SSLContext using a TrustManager that trusts anything (this use-case is one of the very few reasons to use such a trust manager). This is only if you suspect the remote cert won't be trusted.
      • Get an SSLSocketFactory from it.
      • Create an SSLSocket from this factory, using the host name you want to connect to. If you use the host name (and not an InetAddress), this will enable SNI on Java 7, so that would be the equivalent of using -servername as an additional option to your openssl command.
      • Start the handshake (e.g. with startHandhsake())
      • Get the SSLSession from this SSLSocket.
      • For each Certificate in getPeerCertificates():
        • Get its encoded value (as byte[]) using getEncoded()
        • Convert it into PEM, either:
          • Use BouncyCastle's PEMWriter.
          • Use a Base 64 encoder (e.g. Apache Commons), add the BEGIN/END delimiters and split the string with a new line every 64 characters.

          这篇关于JAVA:提取服务器证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆