Я скопировал файлы PEM cert.crt.pem и cert.key.pem в путь к файлу и при выполнении следующего кода для службы REST с подробным URL-адресом, типом сообщения, файлом pem и паролем, он выдает ошибку с «SSLHandshakeException».
Исключение:
Connecteion Ex: 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)
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));
}
}