SSLHandshakeException: PKIX path building failed SunCertPathBuilderException: unable to find valid certification path to requested target

huangapple go评论76阅读模式
英文:

SSLHandshakeException: PKIX path building failed SunCertPathBuilderException: unable to find valid certification path to requested target

问题

以下是您提供的代码的翻译部分:

我已经复制了PEM文件cert.crt.pem和cert.key.pem到文件路径并在执行以下代码时用于REST服务其中包括URL消息类型PEM文件和密码但出现了SSLHandshakeException错误

异常

连接异常javax.net.ssl.SSLHandshakeExceptionsun.security.validator.ValidatorExceptionPKIX路径构建失败sun.security.provider.certpath.SunCertPathBuilderException无法找到请求目标的有效认证路径

代码

class RestWebServicePEM {

    public static void main(String[] args) {
        String url = "<authenticate_url>";
        String msgType = "application/json";
        String method = "POST";
        String pass = "<password>";
        File certKeyFile = new File("cert.crt.pem");
        File privateKeyFile = new File("cert.key.pem");

        HttpsURLConnection con = getSslConnection(url, msgType, method, privateKeyFile, certKeyFile, pass);
        int responseCode = con.getResponseCode();
    }

    private HttpsURLConnection getSslConnection(String inUrl, String inMsgType, String inMethod,
                                                File privateKeyPem, File certificatePem, String password) {
        HttpsURLConnection con = null;
        SocketFactory sslSocketFactory = createSSLSocketFactory(privateKeyPem, certificatePem, password);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        try {
            URL url = new URL(inUrl);
            con = (HttpsURLConnection) url.openConnection();
            con.setSSLSocketFactory(sslSocketFactory);
            if (inMethod == "POST") {
                con.setRequestMethod(inMethod);
                con.setDoOutput(true);
            }

            con.setInstanceFollowRedirects(true);
            con.setConnectTimeout(30000);
            con.setReadTimeout(30000);

            con.setRequestProperty("Content-Type", inMsgType);

            con.connect();
        } catch (Exception e) {
            if (con != null)
                con.disconnect();
            con = null;
        }
        return con;
    }

    private SSLSocketFactory createSSLSocketFactory(File privateKeyPem, File certificatePem, String password) throws Exception {
        SSLContext context = SSLContext.getInstance("TLS");
        KeyStore keystore = createKeyStore(privateKeyPem, certificatePem, password);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, password.toCharArray());
        KeyManager[] km = kmf.getKeyManagers();
        context.init(km, null, null);
        return context.getSocketFactory();
    }

    private KeyStore createKeyStore(File privateKeyPem, File certificatePem, final String password)
            throws Exception, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        X509Certificate[] cert = createCertificates(certificatePem);
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(null);

        PrivateKey key = createPrivateKey(privateKeyPem);
        keystore.setKeyEntry(privateKeyPem.getName(), key, password.toCharArray(), cert);
        return keystore;
    }

    private PrivateKey createPrivateKey(File privateKeyPem) throws Exception {
        BufferedReader r = new BufferedReader(new FileReader(privateKeyPem));
        String s = r.readLine();

        while (s != null) {
            if (s.contains("BEGIN PRIVATE KEY")) {
                break;
            }
            s = r.readLine();
        }

        StringBuilder b = new StringBuilder();
        s = "";
        while (s != null) {
            if (s.contains("END PRIVATE KEY")) {
                break;
            }
            b.append(s);
            s = r.readLine();
        }
        r.close();
        String hexString = b.toString();
        byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
        return generatePrivateKeyFromDER(bytes);
    }

    private X509Certificate[] createCertificates(File certificatePem) throws Exception {
        List<X509Certificate> result = new ArrayList<X509Certificate>();
        BufferedReader r = new BufferedReader(new FileReader(certificatePem));
        String s = r.readLine();
        while (s != null) {
            if (s.contains("BEGIN CERTIFICATE")) {
                break;
            }
            s = r.readLine();
        }

        StringBuilder b = new StringBuilder();
        while (s != null) {
            if (s.contains("END CERTIFICATE")) {
                String hexString = b.toString();
                final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
                X509Certificate cert = generateCertificateFromDER(bytes);
                result.add(cert);
                addMessage("Certificate:" + cert);
                b = new StringBuilder();
            } else {
                if (!s.startsWith("----")) {
                    b.append(s);
                }
            }
            s = r.readLine();
        }
        r.close();

        return result.toArray(new X509Certificate[result.size()]);
    }

    private RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) factory.generatePrivate(spec);
    }

    private X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
    }

}

请注意,我已经将代码中的HTML实体引用(例如“"”)替换为相应的字符。如果您需要更多帮助或有任何其他问题,请随时提问。

英文:

I have copied PEM files cert.crt.pem and cert.key.pem in a file path and on executing the following code for the REST service with the details url, message type, pem file and password, it errors out with "SSLHandshakeException".

Exception:

Connecteion Ex: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

Code:

class RestWebServicePEM {
public static void main(String[] args) {
String url = &quot;&lt;authenticate_url&gt;&quot;;
String msgType = &quot;application/json&quot;;
String method = &quot;POST&quot;;
String pass = &quot;&lt;password&gt;&quot;;
File certKeyFile = new File(&quot;cert.crt.pem&quot;);
File privateKeyFile = new File(&quot;cert.key.pem&quot;);
HttpsURLConnection con = getSslConnection(url, msgType, method, privateKeyFile, certKeyFile, pass);
int responseCode = con.getResponseCode();
}
private HttpsURLConnection getSslConnection(String inUrl, String inMsgType, String inMethod,
File privateKeyPem, File certificatePem, String password) {
HttpsURLConnection con = null;
SocketFactory sslSocketFactory = createSSLSocketFactory(privateKeyPem, certificatePem, password);
HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
try {
URL url = new URL(inUrl);
con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(sslSocketFactory);
if (inMethod == &quot;POST&quot;) {
con.setRequestMethod(inMethod);
con.setDoOutput(true);
}
con.setInstanceFollowRedirects(true);
con.setConnectTimeout(30000);
con.setReadTimeout(30000);
con.setRequestProperty(&quot;Content-Type&quot;, inMsgType);
con.connect();
} catch (Exception e) {
if (con)
con.disconnect();
con = null;
}
return con;
}
private SSLSocketFactory createSSLSocketFactory(File privateKeyPem, File certificatePem, String password) throws Exception {
SSLContext context = SSLContext.getInstance(&quot;TLS&quot;);
KeyStore keystore = createKeyStore(privateKeyPem, certificatePem, password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(&quot;SunX509&quot;);
kmf.init(keystore, password.toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
return context.getSocketFactory();
}
private KeyStore createKeyStore(File privateKeyPem, File certificatePem, final String password)
throws Exception, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
X509Certificate[] cert = createCertificates(certificatePem);
KeyStore keystore = KeyStore.getInstance(&quot;JKS&quot;);
keystore.load(null);
PrivateKey key = createPrivateKey(privateKeyPem);
keystore.setKeyEntry(privateKeyPem.getName(), key, password.toCharArray(), cert);
return keystore;
}
private PrivateKey createPrivateKey(File privateKeyPem) throws Exception {
BufferedReader r = new BufferedReader(new FileReader(privateKeyPem));
String s = r.readLine();
while (s != null) {
if (s.contains(&quot;BEGIN PRIVATE KEY&quot;)) {
break;
}
s = r.readLine();
}
StringBuilder b = new StringBuilder();
s = &quot;&quot;;
while (s != null) {
if (s.contains(&quot;END PRIVATE KEY&quot;)) {
break;
}
b.append(s);
s = r.readLine();
}
r.close();
String hexString = b.toString();
byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
return generatePrivateKeyFromDER(bytes);
}
private X509Certificate[] createCertificates(File certificatePem) throws Exception {
List&lt;X509Certificate&gt; result = new ArrayList&lt;X509Certificate&gt;();
BufferedReader r = new BufferedReader(new FileReader(certificatePem));
String s = r.readLine();
while (s != null) {
if (s.contains(&quot;BEGIN CERTIFICATE&quot;)) {
break;
}
s = r.readLine();
}
StringBuilder b = new StringBuilder();
while (s != null) {
if (s.contains(&quot;END CERTIFICATE&quot;)) {
String hexString = b.toString();
final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
X509Certificate cert = generateCertificateFromDER(bytes);
result.add(cert);
addMessage(&quot;Certificate:&quot;+cert);
b = new StringBuilder();
} else {
if (!s.startsWith(&quot;----&quot;)) {
b.append(s);
}
}
s = r.readLine();
}
r.close();
return result.toArray(new X509Certificate[result.size()]);
}
private RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory factory = KeyFactory.getInstance(&quot;RSA&quot;);
return (RSAPrivateKey) factory.generatePrivate(spec);
}
private X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
CertificateFactory factory = CertificateFactory.getInstance(&quot;X.509&quot;);
return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
}
}

答案1

得分: 1

你可以通过将证书添加到Java密钥库来解决此问题。

  1. 下载证书。

  2. 进入路径<JAVA_HOME>...jre\lib\security。

  3. 将证书放在这里。

  4. 运行密钥工具命令(管理员模式),如果要求输入密码,请输入(密码为changeit):

    keytool -keystore cacerts -importcert -alias "你的别名" -file 证书名称.cer

  5. 现在你可以移除SSL认证代码。

英文:

You can fix this issue by adding certificate to the Java key store.

  1. Download the certificate.

  2. Go to the path <JAVA_HOME>...jre\lib\security.

  3. Keep the certificate here.

  4. Run the key tool command (Administrator mode) type password if it is asking for(changeit)

    keytool -keystore cacerts -importcert -alias "your alisa name" -file certificare name.cer

5.Now you can remove the SSL authentication code.

huangapple
  • 本文由 发表于 2020年8月5日 13:04:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63258721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定