添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Добрый день, понимаю, что вопрос очень простой, но не могу с ходу понять, что делаю не так.

У организации есть необходимость логиниться по токену в сервисах.

Соответственно есть файл сертификата и 6 key файлов.
Есть корневой сертификат минкомсвязи. Добавлять сертификаты нужно по ТЗ именно программно.

Не могу понять, как это все добро програмно добавить в хранилище и послать ssl запрос.
Делаю так:

Код:

package com.company;
import ru.CryptoPro.JCP.JCP;
import ru.CryptoPro.JCP.KeyStore.HDImage.HDImageStore;
import ru.CryptoPro.ssl.Provider;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.logging.Logger;
public class Main {
    private static final String URL =
            "https://stenddss.cryptopro.ru:4430/opensmeidp/ums/";
    public static void main(String[] args) throws Exception {
        System.setProperty("com.sun.security.enableCRLDP", "true");
        System.setProperty("com.ibm.security.enableCRLDP", "true");
        System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
        System.setProperty("ru.CryptoPro.reprov.enableAIAcaIssuers", "true");
        System.setProperty("javax.net.ssl.keyStoreProvider", "JCP");
        System.setProperty("javax.net.ssl.keyStoreType", "HDImageStore");
        //System.setProperty("javax.net.ssl.trustStore", "/etc/ssl/certs/java/cacerts");
        //System.setProperty("javax.net.ssl.trustStoreType", "CertStore");
        //System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
        /*Security.setProperty("ssl.SocketFactory.provider", "ru.CryptoPro.ssl.SSLSocketFactoryImpl");
        Security.setProperty("ssl.ServerSocketFactory.provider", "ru.CryptoPro.ssl.SSLServerSocketFactoryImpl");
        //System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");
        System.setProperty("javax.net.ssl.keyStoreType", "HDImageStore");
        //System.setProperty("javax.net.ssl.keyStore",
        //        "client_exch");
        ////System.setProperty("javax.net.ssl.keyStorePassword", "password");
        System.setProperty("javax.net.ssl.trustStoreType", "HDImageStore");
        final String keystoreName = "HDImageStore";
        final String keystorePass = "password";
        final String keystorePath = "/path/to/keysDir";
        final String certPath = "/path/to/our.cer";
        final String rootCertPath = "/path/to/root/4BC6DC14D97010C41A26E058AD851F81C842415A.cer";
        final String alias = "Cert";
//Запись сертификата в хранилище
        KeyStore ks=addCert(certPath, JCP.HD_STORE_NAME, keystorePass, keystorePath, alias);
        //KeyStore ts=addCert(rootCertPath, JCP.HD_STORE_NAME, "null", "null", "root");
        Certificate rootCert=loadCertificate(new File(rootCertPath));
        KeyStore rootks = KeyStore.getInstance("HDImageStore");
        rootks.load(null,"root".toCharArray());
        rootks.setCertificateEntry("root",rootCert);
        sendTest(ks,keystorePass,rootks);
        System.out.println(HDImageStore.getDir());
        //delCert(keystoreName, keystorePass, keystorePath, alias);
    private static Certificate loadCertificate(File certificateFile) throws Exception{
        try (FileInputStream inputStream = new FileInputStream(certificateFile)) {
            return (Certificate) CertificateFactory.getInstance("X509").generateCertificate(inputStream);
    public static void sendTest(KeyStore keyStore, String keystorePass, KeyStore trustStore) throws Exception {
        // Загрузка хранилища доверенных корневых
        // сертификатов.
        char[] KEY_STORE_PASSWORD = null;
        if (!"null".equalsIgnoreCase(keystorePass)) {
            KEY_STORE_PASSWORD = keystorePass.toCharArray();
        //KeyStore trustStore = KeyStore.getInstance("Corp CA");
        //trustStore.load(null,"changeit".toCharArray());
        KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(Provider.KEYMANGER_ALG);
        kmFactory.init(keyStore, KEY_STORE_PASSWORD);
        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(Provider.TRUSTMANGER_ALG);
        tmFactory.init(trustStore);
        Certificate root=trustStore.getCertificate("root");
        // Инициализация SSL контекста.
        SSLContext sslContext = SSLContext.getInstance(Provider.ALGORITHM);
        sslContext.init(kmFactory.getKeyManagers(), tmFactory.getTrustManagers(), null);
        // Создание подключения.
        java.net.URL url = new URL(URL);
        System.out.println(url);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setSSLSocketFactory(sslContext.getSocketFactory());
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write("{\"Login\":\"RestTestUser\",\"Email\":\"[email protected]\",\"PhoneNumber\":\"+79150510528\"}".getBytes());
        connection.connect();
        // Получение и вывод ответа.
        int responseCode = connection.getResponseCode();
        BufferedReader bufferedReader = null;
        try {
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("Invalid http response: " + responseCode);
            InputStreamReader inputStreamReader = new InputStreamReader(
                    connection.getInputStream(), "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String input;
            while ((input = bufferedReader.readLine()) != null) {
                System.out.println(input);
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            connection.disconnect();
    public static KeyStore addCert(String certPath, String keystoreName,
                                   String keystorePass,
                                   String keystorePath, String alias) throws Exception {
        final CertificateFactory cf = CertificateFactory.getInstance("X509");
        final Certificate rootCert = cf.generateCertificate(
                new BufferedInputStream(new FileInputStream(certPath)));
        /*final KeyStore ks = KeyStore.getInstance(keystoreName);
        char[] KeyStorePass = null;
        if (!"null".equalsIgnoreCase(keystorePass)) {
            KeyStorePass = keystorePass.toCharArray();
        InputStream is = null;
        if (!"null".equalsIgnoreCase(keystorePath)) {
            is = new FileInputStream(keystorePath);
        ks.load(is, KeyStorePass);
        ks.setCertificateEntry(alias, rootCert);
        OutputStream os = null;
        if (!"null".equalsIgnoreCase(keystorePath)) {
            os = new FileOutputStream(keystorePath);
        ks.store(os, KeyStorePass);*/
        HDImageStore.setDir(keystorePath);
        KeyStore ks = KeyStore.getInstance("HDImageStore");
        char[] KeyStorePass = null;
        if (!"null".equalsIgnoreCase(keystorePass)) {
            KeyStorePass = keystorePass.toCharArray();
        ks.load(null,KeyStorePass);
        ks.setCertificateEntry(alias, rootCert);
        Logger.getLogger("LOGGER").info(
                "Recording of a Certificate named \"" + alias + "\" to " +
                        keystoreName + " is completed.");
        return ks;
     * Удаление сертификата из хранилища
     * @param keystoreName тип хранилища
     * @param keystorePass пароль на хранилище
     * @param keystorePath путь к хранилищу
     * @param alias имя
     * @throws Exception е
    public static void delCert(String keystoreName,
                               String keystorePass,
                               String keystorePath, String alias) throws Exception {
        final KeyStore ks = KeyStore.getInstance(keystoreName);
        char[] KeyStorePass = null;
        if (!"null".equalsIgnoreCase(keystorePass)) {
            KeyStorePass = keystorePass.toCharArray();
        InputStream is = null;
        if (!"null".equalsIgnoreCase(keystorePath)) {
            is = new FileInputStream(keystorePath);
        ks.load(is, KeyStorePass);
        if (ks.isCertificateEntry(alias)) ks.deleteEntry(alias);
        OutputStream os = null;
        if (!"null".equalsIgnoreCase(keystorePath)) {
            os = new FileOutputStream(keystorePath);
        ks.store(os, KeyStorePass);
        Logger.getLogger("LOGGER").info(
                "Deleting of a Certificate named \"" + alias + "\" to " +
                        keystoreName + " is completed.");


Сейчас выходит ошибка:
ru.CryptoPro.ssl.SSLSocketImpl a
WARNING: main, handling exception: javax.net.ssl.SSLHandshakeException: ru.CryptoPro.ssl.pc_4.cl_5: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Экспортные ограничения сняты в openjdk-8

Хотелось бы понять почему. Заранее спасибо за помощь.

Отредактировано пользователем 13 мая 2021 г. 19:20:58(UTC) | Причина: добавил про ограничения

Здравствуйте.
1. Вероятно, это ошибка при построении цепочки сертификатов сервера. Если в rootks, который попадает в TrustManagerFactory,
А) действительно помещается корневой сертификат Минкомсвязи и
Б) именно он нужен для цепочки сервера (то есть этот не тестовый сервер с цепочкой, оканчивающейся иным сертификатом),
то попробуйте вместо
Цитата:

KeyStore rootks = KeyStore.getInstance("HDImageStore");

задать
Цитата:

KeyStore rootks = KeyStore.getInstance("CertStore");

2. Вы в коде sendTest уже создаете SSLContext sslContext и передаете его в connection:
Цитата:

connection.setSSLSocketFactory(sslContext.getSocketFactory());

поэтому свойства вроде
Цитата:

System.setProperty("javax.net.ssl.keyStoreProvider", "JCP");
System.setProperty("javax.net.ssl.keyStoreType", "HDImageStore");

излишни и не нужны.
3. Если пп.1-2 не помогут, то соберите и приложите полный лог, включив логирование так: https://support.cryptopr...lirovnija-kriptopro-jtls где
Цитата:

java.util.logging.ConsoleHandler.level=ALL
ru.CryptoPro.ssl.SSLLogger.level=ALL

Тех. поддержка
База знаний
Логирование JCP
Логирование JTLS
Тест JCP и сбор диаг. информации
Скачать JCP, JCSP и JTLS
Скачать Android CSP + SDK
Спасибо за помощь, однако все равно что-то не выходит коннект. Код следующий:
Код:

package com.company;
import org.apache.commons.codec.cli.Digest;
import org.apache.commons.codec.digest.DigestUtils;
import ru.CryptoPro.JCP.JCP;
import ru.CryptoPro.JCP.KeyStore.HDImage.HDImageStore;
import ru.CryptoPro.ssl.Provider;
import javax.crypto.SecretKey;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.util.logging.Logger;
public class Main {
    private static final String URL =
            "https://stenddss.cryptopro.ru:4430/opensmeidp/ums/"
    public static String getCertThumbprint(Certificate cert) throws CertificateEncodingException {
        return  DatatypeConverter.printHexBinary(DigestUtils.getSha1Digest().digest(cert.getEncoded()));
    public static void main(String[] args) throws Exception {
        System.setProperty("com.sun.security.enableCRLDP", "true");
        System.setProperty("com.ibm.security.enableCRLDP", "true");
        System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
        System.setProperty("ru.CryptoPro.reprov.enableAIAcaIssuers", "true");
        final String keystoreName = "HDImageStore";
        final String keystorePass = "1234567890";
        final String keystorePath = "/path/to/cert/main.000/";
        final String certPath = "/path/to/cert/main.cer";
        final String rootCertPath = "/path/to/rootcert/4BC6DC14D97010C41A26E058AD851F81C842415A.cer";
        final String alias = "Cert";
        //Запись сертификата в хранилище
        KeyStore ks=addCert(certPath, JCP.HD_STORE_NAME, keystorePass, keystorePath, alias);
        //KeyStore ts=addCert(rootCertPath, JCP.HD_STORE_NAME, "null", "null", "root");
        Certificate rootCert=loadCertificate(new File(rootCertPath));
        String thumbPrint=getCertThumbprint(loadCertificate(new File(certPath)));
        System.out.println(thumbPrint);
        KeyStore rootks = KeyStore.getInstance("CertStore");
        rootks.load(null,"root".toCharArray());
        rootks.setCertificateEntry("root",rootCert);
        sendTest(URL+thumbPrint,ks,keystorePass,rootks);
        System.out.println(HDImageStore.getDir());
    public static void sendTest(String urlS,KeyStore keyStore, String keystorePass, KeyStore trustStore) throws Exception {
        KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(Provider.KEYMANGER_ALG);
        kmFactory.init(keyStore, keystorePass.toCharArray());
        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(Provider.TRUSTMANGER_ALG);
        tmFactory.init(trustStore);
        // Инициализация SSL контекста.
        SSLContext sslContext = SSLContext.getInstance(Provider.ALGORITHM);
        sslContext.init(kmFactory.getKeyManagers(), tmFactory.getTrustManagers(), null);
        // Создание подключения.
        java.net.URL url = new URL(urlS);
        System.out.println(url);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setSSLSocketFactory(sslContext.getSocketFactory());
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write("{\"Login\":\"RestTestUser\",\"Email\":\"[email protected]\",\"PhoneNumber\":\"+79150510528\"}".getBytes());
        connection.connect();
        // Получение и вывод ответа.
        int responseCode = connection.getResponseCode();
        BufferedReader bufferedReader = null;
        try {
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("Invalid http response: " + responseCode);
            InputStreamReader inputStreamReader = new InputStreamReader(
                    connection.getInputStream(), "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String input;
            while ((input = bufferedReader.readLine()) != null) {
                System.out.println(input);
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            connection.disconnect();
    private static Certificate loadCertificate(File certificateFile) throws Exception{
        try (FileInputStream inputStream = new FileInputStream(certificateFile)) {
            return (Certificate) CertificateFactory.getInstance("X509").generateCertificate(inputStream);
    public static KeyStore addCert(String certPath, String keystoreName,
                                   String keystorePass,
                                   String keystorePath, String alias) throws Exception {
        final CertificateFactory cf = CertificateFactory.getInstance("X509");
        HDImageStore.setDir(keystorePath);
        final Certificate rootCert = cf.generateCertificate(
                new BufferedInputStream(new FileInputStream(certPath)));
        KeyStore ks = KeyStore.getInstance("HDImageStore");
        char[] KeyStorePass = null;
        if (!"null".equalsIgnoreCase(keystorePass)) {
            KeyStorePass = keystorePass.toCharArray();
        ks.load(null,KeyStorePass);
        /*SecretKey secretKey = getSecretKey();
        KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
        KeyStore.ProtectionParameter protectionParameter=new  KeyStore.ProtectionParameter();
        ks.setEntry("keyAlias2", secretKeyEntry, new KeyStore.PasswordProtection(KeyStorePass));*/
        ks.setCertificateEntry(alias, rootCert);
        Logger.getLogger("LOGGER").info(
                "Recording of a Certificate named \"" + alias + "\" to " +
                        keystoreName + " is completed.");
        return ks;


Лог следующий:


/usr/lib/jvm/java-8-openjdk-amd64/bin/java -javaagent:/home/user/bin/idea-IC/lib/idea_rt.jar=40341:/home/user/bin/idea-IC/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/charsets.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/ASN1P.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/AdES-core.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/CAdES.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/J6CF.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/J6Oscar.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCP.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCPControlPane.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCPRequest.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCPRevCheck.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCPRevTools.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCPinst.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCPxml.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCSP.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/JCryptoP.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/Rutoken.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/XAdES.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/XMLDSigRI.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/asn1rt.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/cpSSL.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/forms_rt.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/icedtea-sound.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jaccess.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/java-atk-wrapper.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/localedata.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jce.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfr.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jsse.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/management-agent.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/resources.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/rt.jar:/home/user/IdeaProjects/certTest/out/production/certTest:/home/user/IdeaProjects/certTest/commons-codec-1.15.jar com.company.Main
May 13, 2021 8:54:06 PM ru.CryptoPro.JCSP.MSCAPI.cl_6 enumInstalledProviders
INFO: Provider with type 24 not found.
May 13, 2021 8:54:06 PM ru.CryptoPro.JCSP.MSCAPI.cl_6 enumInstalledProviders
INFO: Provider with type 24 not found.
May 13, 2021 8:54:07 PM ru.CryptoPro.JCP.tools.Starter check
INFO: Loading JCP 2.0.40424
May 13, 2021 8:54:07 PM ru.CryptoPro.JCP.tools.Starter check
INFO: JCP loaded.
May 13, 2021 8:54:07 PM com.company.Main addCert
INFO: Recording of a Certificate named "Cert" to HDImageStore is completed.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_38 <init>
WARNING: %% No appropriate keys for handshake
PATH: /path/to/cert/main.000/
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_38 <init>
WARNING: %% No appropriate keys for handshake
PATH: /path/to/cert/main.000/
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_121 a
FINE:
%% adding as trusted certificates %%

May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_121 a
FINE:
%% adding as trusted certificates %%

May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_121 a
FINE: adding as trusted cert:
Subject: CN=Минкомсвязь России, OID.1.2.643.3.131.1.1=#120C303037373130343734333735, OID.1.2.643.100.1=#120D31303437373032303236373031, O=Минкомсвязь России, STREET="улица Тверская, дом 7", L=г. Москва, ST=77 Москва, C=RU, [email protected]
Issuer: CN=Минкомсвязь России, OID.1.2.643.3.131.1.1=#120C303037373130343734333735, OID.1.2.643.100.1=#120D31303437373032303236373031, O=Минкомсвязь России, STREET="улица Тверская, дом 7", L=г. Москва, ST=77 Москва, C=RU, [email protected]
Algorithm: GOST3410_2012_256
Serial number: 0x4e6d478b26f27d657f768e025ce3d393
Valid from Fri Jul 06 15:18:06 MSK 2018
until Tue Jul 01 15:18:06 MSK 2036

May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_121 a
FINE: adding as trusted cert:
Subject: CN=Минкомсвязь России, OID.1.2.643.3.131.1.1=#120C303037373130343734333735, OID.1.2.643.100.1=#120D31303437373032303236373031, O=Минкомсвязь России, STREET="улица Тверская, дом 7", L=г. Москва, ST=77 Москва, C=RU, [email protected]
Issuer: CN=Минкомсвязь России, OID.1.2.643.3.131.1.1=#120C303037373130343734333735, OID.1.2.643.100.1=#120D31303437373032303236373031, O=Минкомсвязь России, STREET="улица Тверская, дом 7", L=г. Москва, ST=77 Москва, C=RU, [email protected]
Algorithm: GOST3410_2012_256
Serial number: 0x4e6d478b26f27d657f768e025ce3d393
Valid from Fri Jul 06 15:18:06 MSK 2018
5DA578E8CF356ED4EECA090D9EB81ADB9621E331
until Tue Jul 01 15:18:06 MSK 2036

May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: SSLContextImpl init.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: SSLContextImpl init.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: trigger seeding of SecureRandom
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: trigger seeding of SecureRandom
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: done seeding SecureRandom
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: done seeding SecureRandom
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: SSLContextImpl initialized.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: SSLContextImpl initialized.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
FINE: DefaultSSLContext getDefaultKeyManager().
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
FINE: DefaultSSLContext getDefaultKeyManager().
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: keyStore is :
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: keyStore is :
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: keyStore type is :
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: keyStore type is :
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: keyStore provider is :
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: keyStore provider is :
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: init keystore
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: init keystore
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: init keymanager of type GostX509
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext l
INFO: init keymanager of type GostX509
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_38 <init>
WARNING: %% No appropriate keys for handshake
PATH: /home/user/tmp/cert/main.000/
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_38 <init>
WARNING: %% No appropriate keys for handshake
PATH: /home/user/tmp/cert/main.000/
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore is : No File Available, using empty keystore.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore is : No File Available, using empty keystore.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore type is : CertStore
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore type is : CertStore
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore provider is :
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore provider is :
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: init truststore
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: init truststore
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_121 a
FINE:
%% adding as trusted certificates %%

May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_121 a
FINE:
%% adding as trusted certificates %%

May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: SSLContextImpl init.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: SSLContextImpl init.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: trigger seeding of SecureRandom
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: trigger seeding of SecureRandom
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: done seeding SecureRandom
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: done seeding SecureRandom
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: SSLContextImpl initialized.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl engineInit
INFO: SSLContextImpl initialized.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext <init>
INFO: DefaultSSLContext initialized.
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLContextImpl$DefaultSSLContext <init>
INFO: DefaultSSLContext initialized.
https://eaisto.gibdd.ru/...EECA090D9EB81ADB9621E331
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSessionImpl <init>
FINE: %% Initialized: [Session-1, SSL_NULL_WITH_NULL_NULL]
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSessionImpl <init>
FINE: %% Initialized: [Session-1, SSL_NULL_WITH_NULL_NULL]
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_58 a
FINE: Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_58 a
FINE: Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl setSoTimeout
FINE: main, setSoTimeout(0) called
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl setSoTimeout
FINE: main, setSoTimeout(0) called
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_15 a
FINE: %% No cached client session
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_15 a
FINE: %% No cached client session
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_42 f
FINE: *** ClientHello, TLSv1
RandomCookie: GMT: 1604150975 bytes = { 102, 104, 55, 169, 73, 129, 208, 10, 70, 177, 189, 117, 197, 207, 20, 61, 56, 230, 177, 218, 141, 75, 45, 12, 89, 140, 92, 97 }
Session ID: {}
Cipher Suites: [TLS_CIPHER_2012, TLS_CIPHER_2001]
Compression Methods: { 0 }
Extension ext_hash_and_mac_alg_select, ext_hash_and_mac_alg_select: [48, 32, 48, 30, 48, 8, 6, 6, 42, -123, 3, 2, 2, 9, 48, 8, 6, 6, 42, -123, 3, 2, 2, 22, 48, 8, 6, 6, 42, -123, 3, 2, 2, 23]
Extension renegotiation_info, renegotiated_connection: <empty>
***

May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.cl_42 f
FINE: *** ClientHello, TLSv1
RandomCookie: GMT: 1604150975 bytes = { 102, 104, 55, 169, 73, 129, 208, 10, 70, 177, 189, 117, 197, 207, 20, 61, 56, 230, 177, 218, 141, 75, 45, 12, 89, 140, 92, 97 }
Session ID: {}
Cipher Suites: [TLS_CIPHER_2012, TLS_CIPHER_2001]
Compression Methods: { 0 }
Extension ext_hash_and_mac_alg_select, ext_hash_and_mac_alg_select: [48, 32, 48, 30, 48, 8, 6, 6, 42, -123, 3, 2, 2, 9, 48, 8, 6, 6, 42, -123, 3, 2, 2, 22, 48, 8, 6, 6, 42, -123, 3, 2, 2, 23]
Extension renegotiation_info, renegotiated_connection: <empty>
***

May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl b
FINE: main, RECV TLSv1 ALERT: fatal, description = handshake_failure
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl b
FINE: main, RECV TLSv1 ALERT: fatal, description = handshake_failure
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl h
FINE: main called closeSocket()
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl h
FINE: main called closeSocket()
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl a
WARNING: main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl a
WARNING: main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl close
FINE: main called close()
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl close
FINE: main called close()
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl d
FINE: main, called closeInternal(true)
May 13, 2021 8:54:07 PM ru.CryptoPro.ssl.SSLSocketImpl d
FINE: main, called closeInternal(true)
Exception in thread "main" javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at ru.CryptoPro.ssl.cl_2.a(Unknown Source)
at ru.CryptoPro.ssl.cl_2.a(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.b(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.a(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.n(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.b(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1340)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1315)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:264)
at com.company.Main.sendTest(Main.java:110)
at com.company.Main.main(Main.java:78)
Если вы подключаетесь к https://eaisto.gibdd.ru/...EECA090D9EB81ADB9621E331 то там ведь не ГОСТ TLS - сертификат сервера имеет открытый ключ на алгоритме RSA (если открыть в браузере). JTLS поддерживает только ГОСТ и шлет соответствующие алгоритмы.
И срок сертификата сервера истек (хотя это не имеет значения).

Отредактировано пользователем 13 мая 2021 г. 21:39:51(UTC) | Причина: Не указана

Тех. поддержка
База знаний
Логирование JCP
Логирование JTLS
Тест JCP и сбор диаг. информации
Скачать JCP, JCSP и JTLS
Скачать Android CSP + SDK
Тогда не совсем понятно, как работать и с JTLS и с RSA.

Пытаюсь уже не добавляя что-то простучаться на сайт с заведомо рабочим сертификатом:

Код:

    public static void main(String[] args) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
            //Define a postRequest request
            HttpPost postRequest = new HttpPost("https://ya.ru");
            //Set the API media type in http content-type header
            postRequest.addHeader("content-type", "application/xml");
            //Set the request post body
            StringEntity userEntity = new StringEntity("test");
            postRequest.setEntity(userEntity);
            //Send the request; It will immediately return the response in HttpResponse object if any
            HttpResponse response = httpClient.execute(postRequest);
            //verify the valid error code first
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 201)
                throw new RuntimeException("Failed with HTTP error code : " + statusCode);
        finally
            //Important: Close the connect
            httpClient.getConnectionManager().shutdown();


выдает ошибку:
Цитата:
May 14, 2021 3:53:43 PM ru.CryptoPro.JCSP.MSCAPI.cl_6 enumInstalledProviders
INFO: Provider with type 24 not found.
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore is : No File Available, using empty keystore.
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore is : No File Available, using empty keystore.
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore type is : CertStore
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore type is : CertStore
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore provider is :
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: trustStore provider is :
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: init truststore
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.TrustManagerFactoryImpl a
INFO: init truststore
May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.cl_121 a
FINE:
%% adding as trusted certificates %%

May 14, 2021 3:53:43 PM ru.CryptoPro.ssl.cl_121 a
FINE:
%% adding as trusted certificates %%

May 14, 2021 3:53:44 PM ru.CryptoPro.JCSP.MSCAPI.cl_6 enumInstalledProviders
INFO: Provider with type 24 not found.
Exception in thread "main" javax.net.ssl.SSLException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.ssl.Alert.createSSLException(Alert.java:133)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:324)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:267)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:262)
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1554)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:441)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:436)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at com.company.Main.main(Main.java:101)
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at ru.CryptoPro.ssl.pc_4.cl_2.<init>(Unknown Source)
at ru.CryptoPro.ssl.pc_4.cl_4.a(Unknown Source)
at ru.CryptoPro.ssl.cl_121.a(Unknown Source)
at ru.CryptoPro.ssl.cl_121.a(Unknown Source)
at ru.CryptoPro.ssl.cl_121.a(Unknown Source)
at ru.CryptoPro.ssl.cl_121.checkServerTrusted(Unknown Source)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369)
at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:377)
at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444)
at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422)
at sun.security.ssl.TransportContext.dispatch(TransportContext.java:182)
at sun.security.ssl.SSLTransport.decode(SSLTransport.java:152)
at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1383)
at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1291)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:435)
... 14 more
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200)
at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120)
at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104)
... 31 more


Правильно ли я понимаю, что при установке JTLS я лишаюсь возможности делать запросы https c ключем RSA?
1. Если вы используете JCP 2.0 для java 7-8, то после установки cpSSL.jar в JRE/lib/security/java.security будут свойства:
Цитата:

ssl.KeyManagerFactory.algorithm=GostX509
ssl.TrustManagerFactory.algorithm=GostX509
ssl.SocketFactory.provider=ru.CryptoPro.ssl.SSLSocketFactoryImpl
ssl.ServerSocketFactory.provider=ru.CryptoPro.ssl.SSLServerSocketFactoryImpl

Нужно первые 2 вернуть к исходному виду:
Цитата:

ssl.KeyManagerFactory.algorithm=SunX509
ssl.TrustManagerFactory.algorithm=PKIX

А вторые два - закомментировать (#).
2. Если вы используете JCP 2.0-A для java 10+ и задали указанные выше свойства программно, то нужно после строки Security.addProvider(new Provider()) в вашем коде, если вы добавляете провайдеры программно, добавить:
Цитата:

Security.setProperty("ssl.KeyManagerFactory.algorithm", "SunX509");
Security.setProperty("ssl.TrustManagerFactory.algorithm", "PKIX");
Security.setProperty("ssl.SocketFactory.provider", "");
Security.setProperty("ssl.ServerSocketFactory.provider", "");

Если используете JCP 2.0-A для java 10+ и задали указанные свойства в JRE/lib/security/java.security, то см. п.1.

Отредактировано пользователем 14 мая 2021 г. 18:30:56(UTC) | Причина: Не указана