客户端访问https站点(自定义证书)

本文介绍了客户端通过HTTPS访问使用自定义证书的服务器的两种方法:一是将服务器证书导入JDK的安全证书库,二是程序中手动加载证书。在Java客户端访问时可能会遇到证书异常,解决的关键在于证书的CN需与服务器域名一致。

客户端访问服务器端的几种方式(Https)

按照 Glassfish4.1和Tomcat配置Https访问 设置好服务器端的https访问后,客户端可通过以下几种方式访问服务器端。

  • 浏览器方式
    用户在浏览器中输入相应url后,浏览器会弹出警告(由于使用了未认证的自定义证书),此时确认安全例外就可继续访问。

  • 终端方式
    用户使用linux命令curl https://test.com连接服务器,此时同样因为证书未被认证而会出现如下错误。

    curl: (60) Issuer certificate is invalid.
    More details here: http://curl.haxx.se/docs/sslcerts.html
    
    curl performs SSL certificate verification by default, using a "bundle"
     of Certificate Authority (CA) public keys (CA certs). If the default
     bundle file isn't adequate, you can specify an alternate file
     using the --cacert option.
    If this HTTPS server uses a certificate signed by a CA represented in
     the bundle, the certificate verification probably failed due to a
     problem with the certificate (it might be expired, or the name might
     not match the domain name in the URL).
    If you'd like to turn off curl's verification of the certificate, use
     the -k (or --insecure) option.
    

    根据错误提示,有两种解决方案:

    • 添加参数“-k”关闭证书检查
    • 添加参数“–cacert cert_location”来指明证书位置,”cert_location“是从浏览器导出的该网站证书的位置。
  • java 程序
    在java client程序中访问服务器时会抛出如下异常,解决方法见下一小节。

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building 
    failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    

java client 访问服务器端(Https)

java程序通过Https访问服务器端,通常会抛出异常,解决方法有以下两种。

1. 方式一

将服务器端的证书导入到“${JAVA_HOME}/jre/lib/security/cacerts”。其中,服务器端的证书可以通过浏览器导出,也可登录到服务器端获取。之后,在客户端执行如下命令

sudo keytool -list -alias ${alias} -keystore cacerts # 查看旧的证书(若导入过)

sudo keytool -delete -alias ${alias} -keystore cacerts # 删除旧的证书(若导入过)

sudo keytool -import -alias ${alias} -keystore ${JAVA_HOME}/jre/lib/security/cacerts -file ${path-to-certificate-file}

alias {JAVA_HOME} 是自己的java安装目录,
${path-to-certificate-file} 是从浏览器端导出的证书。

2. 方式二

方式一的原理是将所需证书存到jdk中安全证书的默认位置,同样,我们可以在程序中将证书手动加载进来,这就是方式二,见参考文章2的“方法2”或者参考文章3。

特别注意:在创建证书时,“CN”需设置成自己的主机域名,否则即使按照以上方法设置,仍然会报异常,如下,

javax.net.ssl.SSLException: Certificate for <lyhadoop2.com> doesn't match common name of the certificate subject: sama

该异常显示,需要连接的服务器的域名为“lyhadoop2.com”,可是证书里的“common name”却为“sama”,两者不匹配!


参考文章

1.Java安全通信:HTTPS与SSL
2.Java 使用自签证书访问https站点
3.数字证书及安全加密(二)tomcat单向SSL验证及服务调用
4. Tomcat SSL配置及Tomcat CA证书安装
5.java client访问https server(客户端代码、服务器端配置)
6. java在访问https资源时,忽略证书信任问题
7.Java的HttpClient如何去支持无证书访问https

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值