java 获取服务器证书,JAVA:提取服务器证书

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.

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

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:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值