在 java 中的何处为 SSLException 添加证书?

Where to add certificate for SSLException in java?

我正在使用下面的代码发送 OTP 但我收到错误消息:

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at responseMessage = connection.getResponseMessage();

我找到了几个解决方案,但不确定答案的实施情况。

public Boolean sendSmsOTP(String MobileNumber, String OTPKey) {
    logDebugInfo("In sendSmsOTP ", LOG_TYPE_INFORMATIVE);
    HttpURLConnection connection;
    int responseCode;
    String requestData, responseMessage;
    URL smsUrl;
    URI uri;
    String mobileNumber = MobileNumber.replace("+91", "");
    try {
        logDebugInfo("Mobile Number : " + mobileNumber + "  OTP : " + OTPKey, LOG_TYPE_INFORMATIVE);
        requestData = gResourceBundle.getString("RequestSMSData");
        requestData = requestData.replace("[MobileNumber]", mobileNumber.trim());
        requestData = requestData.replace("[OTPKEY]", OTPKey);
        requestData = requestData.replace("[ ]", "%20");
        requestData = requestData.replace(" ", "%20");
        System.out.println(requestData.toString());
        uri = new URI(requestData);
        smsUrl = uri.toURL();
        logDebugInfo("URL : " + smsUrl.toString(), LOG_TYPE_INFORMATIVE);

        connection = (HttpURLConnection) smsUrl.openConnection();
        connection.setDoOutput(false);
        connection.setDoInput(true);

        System.out.println("Manish negi -> "+connection.toString());

        responseMessage = connection.getResponseMessage();
        logDebugInfo("Response Message from SMS server " + responseMessage, LOG_TYPE_INFORMATIVE);
        responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            connection.disconnect();
            System.out.println("OTP GENERATED");
            return true;
        } else {
            connection.disconnect();
            return false;
        }
    } catch (Exception e) {
        logErrorInfo("Exception in sendSmsOTP function()..." + e.getMessage());
        logDebugInfo("Exception in sendSmsOTP function()..." + e.getMessage(), LOG_TYPE_CRITICAL);
        gResultMessage = gResultMessage.replace("Error Code", "CA01");
        gReturnResponse = getJSONString(gErrorResponse, gResultMessage);
        e.printStackTrace();
        return false;
    }
}

此代码抛出以下错误:

根据我的经验,此错误消息通常意味着您正在尝试使用自签名证书与服务器建立 TLS 连接。如果是这种情况,解决方案通常是将服务器的证书添加到您的客户端 运行 所在的 JVM 的证书存储中。

如果证书在名为 server.crt 的文件中,则可以使用 JVM 附带的 keytool 添加它,如下所示:

keytool -import -noprompt \
  -storepass changeit \
  -alias some_alias \
  -keystore $JAVA_HOME/jre/lib/security/cacerts \
  -file server.crt

您可以 obtain the server's certificate using openssl 使用这样的命令:

 openssl s_client -showcerts -connect www.example.com:443 </dev/null

首先,您需要安装服务器证书或将其添加到客户端 JVM 密钥库中。您可以按照 anothernode 的说明通过 keytool 安装它,或者您可以使用基于 GUI 的工具 keyStore Explorer。

一旦您在客户端存储上获得了服务器证书,那么它应该就可以解决了。您可以使用 keyStore Explorer 工具检查证书是否已添加到客户端密钥库吗?