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

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

问题描述

我需要帮助以获取适当的代码以获取服务器证书-有效和无效,由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 CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert

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

This returns the (don't know the encryption) chain of certificates on gmail. I want my 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.

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

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