英文:
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.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败: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 = "<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)
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));
}
}
答案1
得分: 1
你可以通过将证书添加到Java密钥库来解决此问题。
-
下载证书。
-
进入路径<JAVA_HOME>...jre\lib\security。
-
将证书放在这里。
-
运行密钥工具命令(管理员模式),如果要求输入密码,请输入(密码为changeit):
keytool -keystore cacerts -importcert -alias "你的别名" -file 证书名称.cer
-
现在你可以移除SSL认证代码。
英文:
You can fix this issue by adding certificate to the Java key store.
-
Download the certificate.
-
Go to the path <JAVA_HOME>...jre\lib\security.
-
Keep the certificate here.
-
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论