简体   繁体   English

检查证书是否有效

[英]Check whether the certificate is valid or not

I have the java code like this : 我有这样的java代码:

        URL url = new URL(endPoint);
        String encoding = Base64.encodeBase64String(this.key.getBytes());

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

which is opening a ssl connection. 这是打开一个ssl连接。 Lets say the endPoint does uses a self-singed certificate and act as a original website. 让我们说endPoint确实使用了自签名证书并充当原始网站。 Is it possible to prevent these sort of things in the java code? 是否有可能在java代码中阻止这些事情?

Thanks in advance. 提前致谢。

By default, the SSL implementation in Java checks against a list of trusted certification authorities, which is included in the Java VM. 默认情况下,Java中的SSL实现会检查Java VM中包含的受信任证书颁发机构列表。 Unless you extend the default trust store, specify a different trust store at run time or provide your own implementation of a TrustManager and/or HostnameVerifier , you will not be able to make an SSL connection to a server with a self-signed certificate. 除非您扩展默认信任库,在运行时指定其他信任库或提供您自己的TrustManager和/或HostnameVerifier实现,否则您将无法与具有自签名证书的服务器建立SSL连接。

If you for some reason need access to the server certificates after you have established the connection, you can get these from an HttpsURLConnection like this: 如果由于某种原因需要建立连接访问服务器证书,可以从HttpsURLConnection获取这些,如下所示:

URL url = new URL("https://www.google.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.connect();

for(Certificate crt : conn.getServerCertificates()) {
    System.out.println(crt);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM