Error building certification path for the target

Здравствуйте! Есть следующая проблема: Пытаюсь подписать строку которая приходит от сервиса "Честный ЗНАК". Использовал их руководство: TRUE API (596 страница) Изменил код из руководства:...

Форум КриптоПро
 » 
Средства криптографической защиты информации
 » 
КриптоПро JCP, JavaTLS
 » 
Ошибка «Error occurred during building the certification path for the target» при подписании


Offline

SyperOleg2021

 


#1
Оставлено
:

3 ноября 2021 г. 16:54:22(UTC)

SyperOleg2021

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.11.2021(UTC)
Сообщений: 7
Российская Федерация

Сказал(а) «Спасибо»: 2 раз

Здравствуйте! Есть следующая проблема:

Пытаюсь подписать строку которая приходит от сервиса «Честный ЗНАК».
Использовал их руководство: TRUE API (596 страница)

Изменил код из руководства:

Код:


    public String signByCert(String input)
            throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CAdESException {
        List<X509CertificateHolder> chain = new ArrayList<>();
        List<Certificate> certs =
                Arrays.asList(keyStore.getCertificateChain(appSettings.getCryptoPro().getAlias()));

        List<X509Certificate> normalizedCerts = new ArrayList<>();
        certs.forEach(elem -> {
            normalizedCerts.add((X509Certificate) elem);
        });

        certs.forEach(cert -> {
            try {
                chain.add(new X509CertificateHolder(cert.getEncoded()));
            } catch (IOException | CertificateEncodingException e) {
                log.error("Error while building certificate chain", e);
            }
        });
        PrivateKey privateKey = (PrivateKey) (keyStore.getKey(appSettings.getCryptoPro().getAlias(),
                appSettings.getCryptoPro().getPassword().toCharArray()));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        CAdESSignature signature = new CAdESSignature(false);
        signature.setCertificateStore(new CollectionStore(chain));
        final Hashtable table = new Hashtable();
        Attribute attr = new Attribute(CMSAttributes.signingTime,
                new DERSet(new Time(new Date())));
        table.put(attr.getAttrType(), attr);
        AttributeTable attrTable = new AttributeTable(table);
        signature.addSigner(JCP.PROVIDER_NAME, JCP.GOST_DIGEST_OID, JCP.GOST_EL_DH_OID,
                privateKey, normalizedCerts, CAdESType.CAdES_BES, null, false, attrTable, null);
        signature.open(out);
        signature.update(input.getBytes(StandardCharsets.UTF_8));
        signature.close();
        byte[] signedCode = out.toByteArray();
        return Arrays.toString(signedCode);
    }

Однако на строке «signature.addSigner(….)» получаю исключение «Error occurred during building the certification path for the target».

В цепочках всего один сертификат полученный на http://testca2012.cryptopro.ru/ui/

Помогите разрешить проблему.


Вверх


Offline

Евгений Афанасьев

 


#2
Оставлено
:

3 ноября 2021 г. 17:04:47(UTC)

Евгений Афанасьев

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 06.12.2008(UTC)
Сообщений: 3,740
Российская Федерация
Откуда: Крипто-Про

Сказал(а) «Спасибо»: 20 раз
Поблагодарили: 647 раз в 610 постах

Здравствуйте. Ошибка говорит, что не удалось построить цепочку. Скорее всего, в normalizedCerts нет промежуточного и/или корневого сертификата. Кроме того, корневой должен быть установлен в cacerts.

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


Вверх


Offline

SyperOleg2021

 


#3
Оставлено
:

4 ноября 2021 г. 11:22:50(UTC)

SyperOleg2021

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.11.2021(UTC)
Сообщений: 7
Российская Федерация

Сказал(а) «Спасибо»: 2 раз

Автор: Евгений Афанасьев Перейти к цитате

Здравствуйте. Ошибка говорит, что не удалось построить цепочку. Скорее всего, в normalizedCerts нет промежуточного и/или корневого сертификата. Кроме того, корневой должен быть установлен в cacerts.

Да, там сертификаты добавленные только через КриптоПро scp (В данном случае 1). Могу ли я добавить корневые сертификаты в хранилище динамически или они обязательно должны быть в caserts?

Код получения сертификатов из хранилища CSP:

Код:


    public CryptoProService(YAMLAppSettings appSettings)
            throws CertificateException, IOException, NoSuchAlgorithmException,
            KeyStoreException, NoSuchProviderException, UnrecoverableKeyException {
        this.appSettings = appSettings;
        System.setProperty("file.encoding", "UTF-8");
        Security.addProvider(new JCSP());
        Security.addProvider(new RevCheck());
        Security.addProvider(new CryptoProvider());

        keyStore = KeyStore.getInstance(appSettings.getCryptoPro().getLocation(), "JCSP");
        keyStore.load(null, null);
        X509Certificate certificate = (X509Certificate)
                keyStore.getCertificate(appSettings.getCryptoPro().getAlias());
        if (certificate == null) {
            RuntimeException certNotFound = new RuntimeException("Cert not found");
            log.error("Certificate by alias {} not found", appSettings.getCryptoPro().getAlias(), certNotFound);
            throw certNotFound;
        }
    }

Вверх


Offline

SyperOleg2021

 


#4
Оставлено
:

4 ноября 2021 г. 14:04:49(UTC)

SyperOleg2021

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.11.2021(UTC)
Сообщений: 7
Российская Федерация

Сказал(а) «Спасибо»: 2 раз

Загрузил сертификаты в cacerts и в цепочку сертификатов, однако теперь получаю следующую ошибку:

Код:


Caused by: ru.CryptoPro.AdES.exception.AdESException: Root certificate: serial 3453c7b0071add9ab4c5fc8a8451f97a7, subject CN="Тестовый головной УЦ ООО "КРИПТО-ПРО" ГОСТ 2012 (УЦ 2.0)", O="ООО "КРИПТО-ПРО"", STREET=ул. Сущёвский вал д. 18, L=Москва, ST=77 Москва, OID.1.2.643.100.1=#120D31303337373030303835343434, EMAILADDRESS=info@cryptopro.ru, OID.1.2.643.100.4=#120A37373137313037393931, C=RU, issuer CN="Тестовый головной УЦ ООО "КРИПТО-ПРО" ГОСТ 2012 (УЦ 2.0)", O="ООО "КРИПТО-ПРО"", STREET=ул. Сущёвский вал д. 18, L=Москва, ST=77 Москва, OID.1.2.643.100.1=#120D31303337373030303835343434, EMAILADDRESS=info@cryptopro.ru, OID.1.2.643.100.4=#120A37373137313037393931, C=RU, not before Mon Jul 26 12:18:42 YEKT 2021, not after Sat Jul 26 12:18:42 YEKT 2036 is untrusted
	at ru.CryptoPro.AdES.certificate.CertificateChainBuilderImpl.validateIfRootCertificateInTrustStoreAndAddToChain(Unknown Source)
	at ru.CryptoPro.AdES.certificate.CertificateChainBuilderImpl.build(Unknown Source)
	at ru.CryptoPro.AdES.certificate.CertificateChainBuilderImpl.build(Unknown Source)
	... 32 common frames omitted

Вверх


Offline

SyperOleg2021

 


#5
Оставлено
:

4 ноября 2021 г. 14:54:45(UTC)

SyperOleg2021

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.11.2021(UTC)
Сообщений: 7
Российская Федерация

Сказал(а) «Спасибо»: 2 раз

Как выяснилось использовалась не та jdk. Теперь вызывается следующее исключение:

Код:


Caused by: ru.CryptoPro.CAdES.exception.CAdESException: digest OID is null
	at ru.CryptoPro.CAdES.cl_1.addSigner(Unknown Source)
	at ru.CryptoPro.CAdES.cl_1.addSigner(Unknown Source)
	at ru.CryptoPro.CAdES.cl_1.addSigner(Unknown Source)
	at ru.work.markserver.service.CryptoProService.signByCert(CryptoProService.java:122)
	at ru.work.markserver.service.CryptoProService.<init>(CryptoProService.java:71)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211)
	... 21 common frames omitted

Также добавил:

Код:


        System.setProperty("ru.CryptoPro.reprov.enableCRLDP", "true");
        System.setProperty("com.sun.security.enableCRLDP", "true");
        System.setProperty("com.ibm.security.enableCRLDP", "true");

Прикладываю лог с момента вызова функции «signature.addSigner(…)»
crypto_err.log (109kb) загружен 4 раз(а).
Описание проекта

  1. Минимальный набор необходимых библиотек КриптоПРО подключён через локальный maven репозиторий;
  2. Используется spring boot framework;
  3. jdk 16.6 (oracle);
  4. Никаких аргументов запуска явы не прописывалось (из коробки КриптоПро смог считать сертификаты из своего хранилища, поэтому решил, что в этом нет необходимости);
  5. Подключены зависимости org.bouncycastle версии 1.69;
  6. Используется КриптоПро Java CSP и JTLS (5.0.40363-A, для JVM версии 10 и выше)
  7. В системе установлен CryptoPro CSP, а не CryptoPro Java CSP.

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


Вверх


Offline

SyperOleg2021

 


#6
Оставлено
:

6 ноября 2021 г. 12:55:43(UTC)

SyperOleg2021

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.11.2021(UTC)
Сообщений: 7
Российская Федерация

Сказал(а) «Спасибо»: 2 раз

Автор: Евгений Афанасьев Перейти к цитате

Здравствуйте. Ошибка говорит, что не удалось построить цепочку. Скорее всего, в normalizedCerts нет промежуточного и/или корневого сертификата. Кроме того, корневой должен быть установлен в cacerts.

Как правильно подгрузить корневые сертификаты в цепочку сертификатов? Сейчас я их подгружаю из файлов, так как из метода:

Код:


KeyStore keyStore = KeyStore.getInstance("REGISTRY", JCSP.PROVIDER_NAME);
keyStore.getCertificateChain(appSettings.getCryptoPro().getAlias()))

Я получаю только один сертификат полученный на http://testca2012.cryptopro.ru/ui/. А не 3 как должно быть.

Полагаю ошибка «digest OID is null» связана этим


Вверх


Offline

Евгений Афанасьев

 


#7
Оставлено
:

8 ноября 2021 г. 19:36:57(UTC)

Евгений Афанасьев

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 06.12.2008(UTC)
Сообщений: 3,740
Российская Федерация
Откуда: Крипто-Про

Сказал(а) «Спасибо»: 20 раз
Поблагодарили: 647 раз в 610 постах

1. В первом примере вы передаете в addSigner имя провайдера JCP, затем ниже пишете, что используете KeyStore.getInstance(«REGISTRY», JCSP.PROVIDER_NAME) — тут же JCSP. Нужно определиться с провайдером и использовать какой-то один.
2. Ошибка digest OID is null больше похожа на то, что не передается OID алгоритма хеширования в addSigner, хотя в первом примере у вас есть signature.addSigner(JCP.PROVIDER_NAME, JCP.GOST_DIGEST_OID. Это пример актуален? Какая версия JCP/JCSP используется? OID алгоритма ключа соответствует OID алгоритма хеширования (вы передаете OID алгоритма хеша ГОСТ 2001, закрытый ключ тоже ГОСТ 2001)? Попробуйте передать null вместо OID алгоритма хеша и ключа, т.е. signature.addSigner(JCP.PROVIDER_NAME, null, null, …).
3. keyStore.getCertificateChain вернет все сертификаты из ключевого контейнера, тогда как keyStore.getCertificate вернет сертификат подписи. Если в контейнере один сертификат, keyStore.getCertificateChain, соответственно, вернет только его. Именно цепочку он не возвращает и ее не строит. Поэтому «Я получаю только один сертификат полученный на http://testca2012.cryptopro.ru/ui/. А не 3 как должно быть.».
4. «Как правильно подгрузить корневые сертификаты в цепочку сертификатов?» — корневые сертификаты надо ставить в cacerts. Использовать при этом можно известные корневые: Минкомсвязь и др. В ключвом контейнере может и не быть корневого.

Из лога:
09:49:20.022 | [main] | DEBUG | ru.CryptoPro.JCP.tools.JCPLogger — Private key algorithm: GOST3410DH_2012_256
09:49:20.023 | [main] | DEBUG | ru.CryptoPro.JCP.tools.JCPLogger — Evaluated user digest OID: 1.2.643.2.2.9
То есть ключ у вас ГОСТ 2012 256, а OID алгоритма хеширования — 1.2.643.2.2.9 (ГОСТ 2001), «Попробуйте передать null вместо OID алгоритма хеша и ключа, т.е. signature.addSigner(JCP.PROVIDER_NAME, null, null, …)» или передайте signature.addSigner(JCP.PROVIDER_NAME, GOST_DIGEST_2012_256_OID, JCP.GOST_PARAMS_SIG_2012_256_KEY_OID, …).

Отредактировано пользователем 8 ноября 2021 г. 19:45:27(UTC)
 | Причина: Не указана

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


Вверх


Offline

SyperOleg2021

 


#8
Оставлено
:

8 ноября 2021 г. 21:35:24(UTC)

SyperOleg2021

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.11.2021(UTC)
Сообщений: 7
Российская Федерация

Сказал(а) «Спасибо»: 2 раз

Автор: Евгений Афанасьев Перейти к цитате

1. В первом примере вы передаете в addSigner имя провайдера JCP, затем ниже пишете, что используете KeyStore.getInstance(«REGISTRY», JCSP.PROVIDER_NAME) — тут же JCSP. Нужно определиться с провайдером и использовать какой-то один.
2. Ошибка digest OID is null больше похожа на то, что не передается OID алгоритма хеширования в addSigner, хотя в первом примере у вас есть signature.addSigner(JCP.PROVIDER_NAME, JCP.GOST_DIGEST_OID. Это пример актуален? Какая версия JCP/JCSP используется? OID алгоритма ключа соответствует OID алгоритма хеширования (вы передаете OID алгоритма хеша ГОСТ 2001, закрытый ключ тоже ГОСТ 2001)? Попробуйте передать null вместо OID алгоритма хеша и ключа, т.е. signature.addSigner(JCP.PROVIDER_NAME, null, null, …).
3. keyStore.getCertificateChain вернет все сертификаты из ключевого контейнера, тогда как keyStore.getCertificate вернет сертификат подписи. Если в контейнере один сертификат, keyStore.getCertificateChain, соответственно, вернет только его. Именно цепочку он не возвращает и ее не строит. Поэтому «Я получаю только один сертификат полученный на http://testca2012.cryptopro.ru/ui/. А не 3 как должно быть.».
4. «Как правильно подгрузить корневые сертификаты в цепочку сертификатов?» — корневые сертификаты надо ставить в cacerts. Использовать при этом можно известные корневые: Минкомсвязь и др. В ключвом контейнере может и не быть корневого.

Из лога:
09:49:20.022 | [main] | DEBUG | ru.CryptoPro.JCP.tools.JCPLogger — Private key algorithm: GOST3410DH_2012_256
09:49:20.023 | [main] | DEBUG | ru.CryptoPro.JCP.tools.JCPLogger — Evaluated user digest OID: 1.2.643.2.2.9
То есть ключ у вас ГОСТ 2012 256, а OID алгоритма хеширования — 1.2.643.2.2.9 (ГОСТ 2001), «Попробуйте передать null вместо OID алгоритма хеша и ключа, т.е. signature.addSigner(JCP.PROVIDER_NAME, null, null, …)» или передайте signature.addSigner(JCP.PROVIDER_NAME, GOST_DIGEST_2012_256_OID, JCP.GOST_PARAMS_SIG_2012_256_KEY_OID, …).

1. Хочу использовать JCSP, переключался между JCP и JСSP в надежде исправить ошибку. То что в addSigners использовалось JSP заметил и заменил — результата не дало;
2.

  1. Версия JCSP — 5.0.42188-A, JCP — 2.0.42188-A;
  2. Закрытый ключ подписан GOST R 34.10-2012 DH 256 bits;
  3. JCP.GOST_DIGEST_OID и GOST_EL_KEY_OID пытался менять (например на GOST_DH_2012_256_NAME, GOST_EL_2012_256_NAME и др комбинации) — таже ошибка «digest OID is null». null, null как и GOST_DIGEST_2012_256_OID, GOST_PARAMS_SIG_2012_256_KEY_OID тоже результата не дали;

3. Т.е. список сертификатов нужно подгружать со стороннего хранилища, где есть вся цепочка?
4. В cacerts сертификаты добавлены. Думаю я неправильно сформулировал вопрос: при составлении цепочки сертификатов, есть ли какие-то требования к их загрузке (из контейнера сертификатов JCP или из хранилища доверенных Windows) или просто необходим список где будут все сертификаты которые учувствуют в построении цепочки и не имеет значения откуда они будут загружены?

Появился вопрос: org.bouncycastle.* обязательно использовать из скаченного архива (из папки dependencies) или же допустимо тянуть зависимости с maven репозитория?

Сейчас все сертификаты поместил в хранилище сертификатов JCSP, если в цепочке хранить только один сертификат, то получаю ту же ошибку «digest OID is null», а если все 3, то получаю исключение «Private key does not match public key», лог:

Код:


Caused by: java.lang.RuntimeException: Private key does not match public key; error codes: [108] 'Private key does not match public key', 
	at ru.work.markserver.service.NationalService.lambda$new$0(NationalService.java:36)
	at ru.work.markserver.provider.NationalCatalogProvider.updateToken(NationalCatalogProvider.java:73)
	at ru.work.markserver.service.NationalService.postInit(NationalService.java:43)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:389)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:333)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:157)
	... 32 common frames omitted
Caused by: ru.CryptoPro.CAdES.exception.CAdESException: Private key does not match public key
	at ru.CryptoPro.CAdES.cl_1.addSigner(Unknown Source)
	at ru.CryptoPro.CAdES.cl_1.addSigner(Unknown Source)
	at ru.CryptoPro.CAdES.cl_1.addSigner(Unknown Source)
	at ru.work.markserver.service.CryptoProService.signByCert(CryptoProService.java:125)
	at ru.work.markserver.service.NationalService.lambda$new$0(NationalService.java:33)
	... 41 common frames omitted
Caused by: ru.CryptoPro.CAdES.exception.CAdESException: Private key does not match public key
	... 46 common frames omitted
Disconnected from the target VM, address: '127.0.0.1:57909', transport: 'socket'

Process finished with exit code 1

По поводу актуальности: в коде менял только способ загрузки цепочки сертификатов, комбинации OID алгоритмов и в целом подгружал другие версии библиотеки (не для jdk10+ и отдельно JCP). На данный момент у меня исходный пример, за исключением того, что везде используется JCSP

Отредактировано пользователем 8 ноября 2021 г. 22:01:17(UTC)
 | Причина: По поводу актуальности…


Вверх


Offline

Евгений Афанасьев

 


#9
Оставлено
:

8 ноября 2021 г. 22:19:33(UTC)

Евгений Афанасьев

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 06.12.2008(UTC)
Сообщений: 3,740
Российская Федерация
Откуда: Крипто-Про

Сказал(а) «Спасибо»: 20 раз
Поблагодарили: 647 раз в 610 постах

1. «Хочу использовать JCSP» — тогда он должен быть провайдером по умолчанию. Поскольку вы используете версию для Java 10+, установка не производится и в java.security провайдеры, полагаю, не записаны. Если вы добавляете провайдеры с помощью Security.addProvider(), то JCSP должен быть выше JCP, тогда он станет работать по умолчанию:

Цитата:

Security.addProvider(new JCSP());
Security.addProvider(new JCP());
Security.addProvider(new RevCheck());

И его же надо указать в addSigner: addSigner(JCSP.PROVIDER_NAME, …), а не addSigner(JCP.PROVIDER_NAME, …)
2. Обычно достаточно использовать addSigner(provider, null, null, …) для автоопределения OID’ов. Приведите ошибку в этом случае.
3. «Т.е. список сертификатов нужно подгружать со стороннего хранилища, где есть вся цепочка?» — да. сертификаты можно подать из других мест, из файлов, хранилищ. Можно также использовать параметры

Цитата:

System.setProperty(«com.sun.security.enableAIAcaIssuers», «true»);
System.setProperty(«ru.CryptoPro.reprov.enableAIAcaIssuers», «true»);

Про них можно найти информацию на форуме по слову enableAIAcaIssuers, коротко — если а) они заданы, б) есть доступ в сеть и в) в AIA сертификатов есть ссылки на сертификаты центров сертификации, то сертификаты будут скачаны; однако корневой все равно должен быть в cacerts.
4. «есть ли какие-то требования» — нет, просто нужны объекты X509Certificate в списке, множество сертификатов (оно может быть и больше самой цепочки), который просто содержит нужные сертификаты (они будут найдены при построении цепочки).

«Появился вопрос: org.bouncycastle.* обязательно использовать из скаченного архива (из папки dependencies) или же допустимо тянуть зависимости с maven репозитория?» — из любого источника, главное — версия BC 1.60, как в dependencies (тут они для удобства, чтобы не искать):

Цитата:

bcprov-jdk15on-1.60.jar
bcpkix-jdk15on-1.60.jar


Проверьте:
1. провайдер, как в п.1;
2. версию BC, она должна быть 1.60;
3. сделайте addSigner(provider, null, null, …), вроде даже должна быть версия функции без OID хеша и OID ключа.
Если не поможет, приложите цепочку сертификатов, будем проверять и воспроизводить.

Отредактировано пользователем 8 ноября 2021 г. 22:22:01(UTC)
 | Причина: Не указана

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


Вверх

thanks 1 пользователь поблагодарил Евгений Афанасьев за этот пост.

SyperOleg2021

оставлено 08.11.2021(UTC)


Offline

SyperOleg2021

 


#10
Оставлено
:

8 ноября 2021 г. 22:27:50(UTC)

SyperOleg2021

Статус: Новичок

Группы: Участники

Зарегистрирован: 03.11.2021(UTC)
Сообщений: 7
Российская Федерация

Сказал(а) «Спасибо»: 2 раз

Проблема была в использовании библиотек org.bouncycastle.* не из архива, добавил необходимые библиотеки в локальный maven репозиторий и подписание заработало.

Теперь появилась другая проблема, при хешировании ожидается что-то вроде:

Код:


MIIa2QYJKoZIhvcNAQcCoIIayjCCGsYCAQExDjAMBggqh...JRLphTwbI4HQ==

Однако я получаю это:

Код:


0�	*�H��
��0�10*� 0�	*�H��
��$�WUVYERCGDCHJNHZMUMHQYDVGRBRGTF      ��0�/0�ܠ�ԭ6�J�5)'
�0
*�0�V10*�d
77171079911 0	*�H��
	info@cryptopro.ru10*�d
103770008544410	URU10U77 Москва10UМосква1/0-U	&ул. Сущёвский вал д. 181%0#U
ООО "КРИПТО-ПРО"1k0iUbТестовый подчиненный УЦ ООО "КРИПТО-ПРО" ГОСТ 2012 (УЦ 2.0)0
211102162955Z
220202163955Z0��10*��0276140006961604U
-ИП Фазылов Азат Уралович10	URU1"0 U*Азат Уралович10UФазылов1604U-ИП Фазылов Азат Уралович0f0*�0*�$ *�C @gwL�Y~���PU�~�Ǻ����Ah;�PV�o� ˓8`�����`
�|ȏ*�$��x�����0��0U��0	+�70*�.  0U�*�ܴp��R�$%?
Rm�'0&U%0++*�"02	+�7
%0#0
+0
+0	*�"0��+��0��09+0�-http://testca2012.cryptopro.ru/ocsp2/ocsp.srf0[+0�Ohttp://testca2012.cryptopro.ru/aia/758d1bf732d2d0f25f1e0f9e1379ebfc20fe9e2f.crt0U 00*�dq0*�dq0+U$0"�20211102162954Z�20220202162954Z0�*�dp�0�4СКЗИ "КриптоПро CSP" (версия 4.0)1ПАК "КриптоПро УЦ" версии 2.0OСертификат соответствия № СФ/124-3971 от 15.01.2021OСертификат соответствия № СФ/128-3870 от 23.07.20200,*�do#!СКЗИ "КриптоПро CSP"0`UY0W0U�S�Q�Ohttp://testca2012.cryptopro.ru/cdp/758d1bf732d2d0f25f1e0f9e1379ebfc20fe9e2f.crl0*�dr0��U#��0���u��2���_�y�� ��/��X��T0�P10	URU10*�d
77171079911 0	*�H��
	info@cryptopro.ru10*�d
103770008544410U77 Москва10UМосква1/0-U	&ул. Сущёвский вал д. 181%0#U
ООО "КРИПТО-ПРО"1e0cUТестовый головной УЦ ООО "КРИПТО-ПРО" ГОСТ 2012 (УЦ 2.0)���� q��M{KF�B0
*�A Xղ�=�l�/,]nD��n��LUa�$�.����W���Bq؏`"j�:{�-����?|a�}��  1�40�00�m0�V10*�d
77171079911 0	*�H��
	info@cryptopro.ru10*�d
103770008544410	URU10U77 Москва10UМосква1/0-U	&ул. Сущёвский вал д. 181%0#U
ООО "КРИПТО-ПРО"1k0iUbТестовый подчиненный УЦ ООО "КРИПТО-ПРО" ГОСТ 2012 (УЦ 2.0)�ԭ6�J�5)'
�0*� ��	*�H��
	1	*�H��
0	*�H��
	1
211108192434Z0)	*�H��
	4100*� �
*�0/	*�H��
	1" ��dC[��; �1�'RUO?���&���i@�)�]0��*�H��
	/1��0��0��0��0
*� ��1 ���f� x��;J+����Q|T�w��P�0�u0�^��Z0�V10*�d
77171079911 0	*�H��
	info@cryptopro.ru10*�d
103770008544410	URU10U77 Москва10UМосква1/0-U	&ул. Сущёвский вал д. 181%0#U
ООО "КРИПТО-ПРО"1k0iUbТестовый подчиненный УЦ ООО "КРИПТО-ПРО" ГОСТ 2012 (УЦ 2.0)�ԭ6�J�5)'
�0
*�@��'CWas_6d�n[>M&�L"��A�t�77�!��:c>M��`�N�>��G;�$<0��Y�T2&o�      

Вверх

Пользователи, просматривающие эту тему

Guest

Форум КриптоПро
 » 
Средства криптографической защиты информации
 » 
КриптоПро JCP, JavaTLS
 » 
Ошибка «Error occurred during building the certification path for the target» при подписании

Быстрый переход
 

Вы не можете создавать новые темы в этом форуме.

Вы не можете отвечать в этом форуме.

Вы не можете удалять Ваши сообщения в этом форуме.

Вы не можете редактировать Ваши сообщения в этом форуме.

Вы не можете создавать опросы в этом форуме.

Вы не можете голосовать в этом форуме.

  1. Go to URL in your browser:
  • firefox — click on HTTPS certificate chain (the lock icon right next to URL address). Click "more info" > "security" > "show certificate" > "details" > "export..". Pickup the name and choose file type example.cer
  • chrome — click on site icon left to address in address bar, select «Certificate» -> «Details» -> «Export» and save in format «Der-encoded binary, single certificate».
  1. Now you have file with keystore and you have to add it to your JVM. Determine location of cacerts files, eg.
    C:Program Files (x86)Javajre1.6.0_22libsecuritycacerts.

  2. Next import the example.cer file into cacerts in command line (may need administrator command prompt):

keytool -import -alias example -keystore "C:Program Files (x86)Javajre1.6.0_22libsecuritycacerts" -file example.cer

You will be asked for password which default is changeit

Restart your JVM/PC.

source:
http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html

rogerdpack's user avatar

rogerdpack

60.4k35 gold badges259 silver badges379 bronze badges

answered Apr 5, 2016 at 13:00

MagGGG's user avatar

MagGGGMagGGG

18k2 gold badges28 silver badges28 bronze badges

43

After many hours trying to build cert files to get my Java 6 installation working with the new twitter cert’s, I finally stumbled onto an incredibly simple solution buried in a comment in one of the message boards. Just copy the cacerts file from a Java 7 installation and overwrite the one in your Java 6 installation. Probably best to make a backup of the cacerts file first, but then you just copy the new one in and BOOM! it just works.

Note that I actually copied a Windows cacerts file onto a Linux installation and it worked just fine.

The file is located in jre/lib/security/cacerts in both the old and new Java jdk installations.

Hope this saves someone else hours of aggravation.

answered Feb 2, 2014 at 5:55

Jeremy Goodell's user avatar

Jeremy GoodellJeremy Goodell

17.9k5 gold badges34 silver badges51 bronze badges

6

MY UI approach:

  1. Download keystore explorer from here
  2. Open $JAVA_HOME/jre/lib/security/cacerts
  3. enter PW: changeit (Can be changeme on Mac)
  4. Import your .crt file

CMD-Line:

  1. keytool -importcert -file jetty.crt -alias jetty -keystore $JAVA_HOME/jre/lib/security/cacerts
  2. enter PW: changeit (Can be changeme on Mac)

Pritam Banerjee's user avatar

answered Nov 22, 2016 at 14:06

Mike Mitterer's user avatar

Mike MittererMike Mitterer

6,4703 gold badges40 silver badges60 bronze badges

7

1. Check the certificate

Try to load the target URL in browser and view the site’s certificate (usually it’s accessible by the icon with the lock sign. It’s on the left or right side of the browser’s address bar) whether it’s expired or untrusted by other reason.

2. Install latest versions of JRE and JDK

New versions usually come with the updated set of the trusted certificates.

Also if it’s possible, uninstall old versions. This will make misconfiguration errors explicit.

3. Check your configuration:

  • Check where your JAVA_HOME environment variable points to.
  • Check which java version you use to run the program. In IntelliJ check:
    • File -> Project Structure… -> Project Settings -> Project -> Project SDK:
    • File -> Project Structure… -> Platform Settings -> SDKs

4. Copy whole keystore from the new Java version

If you develop under the JDK other than the latest available — try to replace the %JAVA_HOME%/jre/lib/security/cacerts file with the new one from the latest installed JRE (make a backup copy first) as @jeremy-goodell suggests in his answer

5. Add certificate(s) to your keystore

If nothing above solves your problem use keytool to save certificate(s) to the Java’s keystore:

keytool -trustcacerts -keystore "%JAVA_HOME%jrelibsecuritycacerts" -storepass changeit -importcert -alias <alias_name> -file <path_to_crt_file>

File with the certificate can be obtained from the browser as @MagGGG suggests in his answer.

Note 1: you may need to repeat this for every certificate in the chain to you site’s certificate. Start from the root one.

Note 2: <alias_name> should be unique among the keys in the store or keytool will show an error.

To get list of all the certificates in the store you may run:

keytool -list -trustcacerts -keystore "%JAVA_HOME%jrelibsecuritycacerts" -storepass changeit

In case something goes wrong this will help you to remove certificate from the store:

keytool -delete -alias <alias_name> -keystore "%JAVA_HOME%jrelibsecuritycacerts" -storepass changeit

Ali Karaca's user avatar

Ali Karaca

3,0151 gold badge32 silver badges39 bronze badges

answered Sep 13, 2017 at 11:10

Ilya Serbis's user avatar

Ilya SerbisIlya Serbis

20.5k6 gold badges81 silver badges72 bronze badges

3

-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true

It is used for jump the certificate validation.

Warning!

Only use for development purposes for this is unsecure!

Saikat's user avatar

Saikat

13k18 gold badges102 silver badges119 bronze badges

answered Jan 25, 2016 at 15:28

gorums's user avatar

gorumsgorums

1,36712 silver badges5 bronze badges

11

I have stumbled upon this issue which took many hours of research to fix, specially with auto-generated certificates, which unlike Official ones, are quite tricky and Java does not like them that much.

Please check the following link: Solve Problem with certificates in Java

Basically you have to add the certificate from the server to the Java Home certs.

  1. Generate or Get your certificate and configure Tomcat to use it in Servers.xml
  2. Download the Java source code of the class InstallCert and execute it while the server is running, providing the following arguments server[:port]. No password is needed, as the original password works for the Java certs («changeit»).
  3. The Program will connect to the server and Java will throw an exception, it will analyze the certificate provided by the server and allow you to create a jssecerts file inside the directory where you executed the Program (If executed from Eclipse then make sure you configure the Work directory in Run -> Configurations).
  4. Manually copy that file to $JAVA_HOME/jre/lib/security

After following these steps, the connections with the certificate will not generate exceptions anymore within Java.

The following source code is important and it disappeared from (Sun) Oracle blogs, the only page I found it was on the link provided, therefore I am attaching it in the answer for any reference.

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * Originally from:
 * http://blogs.sun.com/andreas/resource/InstallCert.java
 * Use:
 * java InstallCert hostname
 * Example:
 *% java InstallCert ecc.fedora.redhat.com
 */

import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Class used to add the server's certificate to the KeyStore
 * with your trusted certificates.
 */
public class InstallCert {

    public static void main(String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out.println("Usage: java InstallCert [:port] [passphrase]");
            return;
        }

        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            char SEP = File.separatorChar;
            File dir = new File(System.getProperty("java.home") + SEP
                    + "lib" + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }
        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println
                    (" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
        String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }

        X509Certificate cert = chain[k];
        String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);

        OutputStream out = new FileOutputStream("jssecacerts");
        ks.store(out, passphrase);
        out.close();

        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out.println
                ("Added certificate to keystore 'jssecacerts' using alias '"
                        + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }
}

Shashank Agrawal's user avatar

answered May 29, 2015 at 14:52

will824's user avatar

will824will824

2,1834 gold badges26 silver badges28 bronze badges

2

Mac

The accepted answer does not work for Mac as there is no Export button available in Mac (Chrome or Firefox). Please check this answer to download the certificate and follow the next steps as mentioned below:

  1. List all certificates installed in the keystore:
cd $JAVA_HOME/lib/security
keytool -list -keystore cacerts

Notes:

  • The default password of the keystore is: changeit.
  • For Java-8 or lower version use the command, cd $JAVA_HOME/jre/lib/security
  1. Before you import the certificate in the keystore, make a backup of the keystore:
sudo cp cacerts cacerts.bak
  1. Import the downloaded certificate in the keystore:
sudo keytool -importcert -alias youralias -file /path/to/the/downloaded/certificate -keystore cacerts
  1. Check if the certificate is stored in the keystore:
sudo keytool -list -keystore cacerts -alias youralias

If you want to see more detailed information, add the -v flag:

sudo keytool -v -list -keystore cacerts -alias youralias

answered Mar 31, 2021 at 14:39

Arvind Kumar Avinash's user avatar

1

I wanted to import certificate for smtp.gmail.com. The only solution that worked for me is

  1. Enter command to view this certificate

    D:opensslbinopenssl.exe s_client -connect smtp.gmail.com:465
    
  2. Copy and save the lines between -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- into a file, gmail.cer

  3. Run

    keytool -import -alias smtp.gmail.com -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file C:UsersAdminDesktopgmail.cer
    
  4. Enter password: changeit

  5. Click «Yes» to import the certificate

  6. Restart Java

Now run the command and you are good to go.

Ahmed Ashour's user avatar

Ahmed Ashour

4,87810 gold badges36 silver badges52 bronze badges

answered Jan 23, 2017 at 4:53

Sneha Shejwal's user avatar

2

I had a slightly different situation, when both JDK and JRE 1.8.0_112 were present on my system.

I imported the new CA certificates into [JDK_FOLDER]jrelibsecuritycacerts using the already known command:

keytool -import -trustcacerts -keystore cacerts -alias <new_ca_alias> -file <path_to_ca_cert_file>

Still, I kept getting the same PKIX path building failed error.

I added debug information to the java CLI, by using java -Djavax.net.debug=all ... > debug.log. In the debug.log file, the line that begins with trustStore is: actually pointed to the cacerts store found in [JRE_FOLDER]libsecuritycacerts.

In my case the solution was to copy the cacerts file used by JDK (which had the new CAs added) over the one used by the JRE and that fixed the issue.

answered Dec 21, 2016 at 9:19

M. F.'s user avatar

M. F.M. F.

1,62411 silver badges16 bronze badges

1

This isn’t a Twitter-specific answer, but this is the question that comes up when you search for this error. If your system is receiving this error when connecting to a website that appears to have a valid certificate when viewed in a web browser, that probably means that website has an incomplete certificate chain.

For a brief summary of the problem: Certificate Authorities don’t use their Root Certificate to sign just any old certificate. Instead, they (usually) sign intermediate certificates that also have the Certificate Authority flag set (that is, are allowed to sign certificates). Then when you purchase a certificate from a CA, they sign your CSR with one of these intermediate certificates.

Your Java trust store most likely only has the Root Cert, not the intermediate ones.

A misconfigured site might return just their signed cert. Problem: it was signed with an intermediate cert that’s not in your trust store. Browsers will handle this problem by downloading or using a cached intermediate certificate; this maximizes website compatibility. Java and tools like OpenSSL, however, won’t. And that will cause the error in the question.

You can verify this suspicion by using the Qualys SSL Test. If you run that against a site and it says

This server’s certificate chain is incomplete.

then that confirms it. You can also see this by looking at the certification paths and seeing the text Extra Download.

How to fix it: the server administrator needs to configure the web server to return the intermediate certificates as well. For Comodo, for example, this is where the .ca-bundle file comes in handy. For example, in an Apache configuration with mod_ssl, you’d use the SSLCertificateChainFile configuration setting. For nginx, you need to concatenate the intermediate certificates and the signed certificate and use that in the SSL cert configuration. You can find more by searching for «incomplete certificate chain» online.

answered Nov 30, 2017 at 0:13

Reid's user avatar

ReidReid

18.7k5 gold badges37 silver badges37 bronze badges

1

Issue Background:

I was getting following error when i try to run mvn clean install in my project and through Netbeans IDE clean and build option.
This issue is due to certificate not available when we download through NET beans IDE/through command prompt, but able to download the files through the browser.

Error:

Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact com.java.project:product:jar:1.0.32 from/to repo-local (https://url/local-repo): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  

Resolution:

1. Download the certificate of the Url in question:

  • Launch IE by «run as adminstrator» (otherwise, we will not be able to download the certificate)
  • Enter the url in IE-> https://url/local-repo
    (In my case this url had a untrusted certificateenter image description here.)
  • Download the certificate by clicking on Certificate error -> view certificate
  • Select Details tab -> copy to file -> next -> select «DER encoded binary X.509 (.CER)
  • save the certificate in some location, example : c:/user/sheldon/desktop/product.cer
  • Congrats! you have successfully downloaded the certificate for the site

2. Now install the key store to fix the issue.

  • Run the keytool command to append the downloaded keystore into the
    existing certificate file.
  • Command: Below command in the bin folder of jdk (JAVA_HOME).

C:Program FilesJavajdk1.8.0_141jrebin>keytool -importcert -file
«C:/user/sheldon/desktop/product.cer» -alias product -keystore
«C:/Program Files/Java/jdk1.8.0_141/jre/lib/security/cacerts».

  • You will be prompted to enter password. Enter keystore password:
    enter «changeit» again for «Trust this certificate? [no]:», enter
    «yes»

Sample command line commands/output:

keytool -importcert -file "C:/Users/sheldon/Desktop/product.cer" -alias product -keystore "C:/Program iles/Java/jdk1.8.0_141/jre/lib/security/cacerts"
Enter keystore password:
Trust this certificate? [no]:  yes
Certificate was added to keystore
  • Contgrats! now you should have got rid of «PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException» error in your Netbeans IDE.

answered Nov 29, 2017 at 9:01

Barani r's user avatar

Barani rBarani r

1,9731 gold badge23 silver badges24 bronze badges

5

This is a solution but in form of my story with this problem:

I was almost dead trying all the solutions given above(for 3 days ) and nothing worked for me.

I lost all hope.

I contacted my security team regarding this because I was behind a proxy and they told me that they had recently updated their security policy.

Later they issued a new «cacerts» file which contains all the certificates.

I removed the cacerts file which is present inside %JAVA_HOME%/jre/lib/security and it solved my problem.

So if you are facing this issue it might be from your network team also like this.

Saikat's user avatar

Saikat

13k18 gold badges102 silver badges119 bronze badges

answered Jul 31, 2019 at 8:03

Vikash Kumar's user avatar

Vikash KumarVikash Kumar

1,03611 silver badges10 bronze badges

After struggling for half-day, found one more way to solve this problem. I was able to solve this in MAC 10.15.5 ( Catalina). Followed the below steps.

  • This problem occurs when we are running behind a company proxy , In my case its Zscaler.
  • Open Key chain access, export CA certificate.(Select CA certificate, File->export items and save with the desired name)
  • Copy the path of existing cacerts from java folder(/Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home/jre/lib/security/cacerts
    )
  • Open terminal and navigate to the Keytool folder (/Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home/jre/bin
    )
  • Run the below command.
  • Keytool -importcert — file (Path to exported cert from the keychainaccess) -alias (give a name) -keystore (Path of existing cacerts from java folder)
  • sudo Keytool -importcert -file /Users/Desktop/RootCA.cer -alias demo -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home/jre/lib/security/cacerts
  • It will ask for password , give it as : changeit
  • It asks for confirmation , Say : yes

After all of these steps, Quit eclipse and terminal start fresh session.

answered Jul 24, 2020 at 13:05

Venkatesh's user avatar

VenkateshVenkatesh

1412 silver badges8 bronze badges

1

The reason, we get above error is that JDK is bundled with a lot of trusted Certificate Authority(CA) certificates into a file called ‘cacerts’ but this file has no clue of our self-signed certificate. In other words, the cacerts file doesn’t have our self-signed certificate imported and thus doesn’t treat it as a trusted entity and hence it gives the above error.

How to fix the above error

To fix the above error, all we need is to import the self-signed certificate into the cacerts file.

First, locate the cacerts file. We will need to find out the JDK location. If you are running your application through one of the IDE’s like Eclipse or IntelliJ Idea go to project settings and figure out what is the JDK location.
For e.g on a Mac OS typical location of cacerts file would be at this location /Library/Java/JavaVirtualMachines/ {{JDK_version}}/Contents/Home/jre/lib/security
on a Window’s machine it would be under {{Installation_directory}}/{{JDK_version}}/jre/lib/security

Once you have located the cacerts file, now we need to import our self-signed certificate to this cacerts file. Check the last article, if you don’t know how to generate the self-signed certificate correctly.

If you don’t have a certificate file(.crt) and just have a .jks file you can generate a .crt file by using below command. In case you already have a .crt/.pem file then you can ignore below command

##To generate certificate from keystore(.jks file) ####

keytool -export -keystore keystore.jks -alias selfsigned -file selfsigned.crt

Above step will generate a file called selfsigned.crt.Now Import the certificate to cacerts

Now add the certificate to JRE/lib/security/cacerts (trustore)

keytool -importcert -file selfsigned.crt -alias selfsigned -keystore {{cacerts path}}

for e.g

keytool -importcert -file selfsigned.nextgen.crt -alias selfsigned.nextgen -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts

That’s all, restart your application and it should work fine. If it still doesn’t work and get an SSL handshake exception. It probably means you are using different domain then registered in the certificate.

The Link with detailed explanation and step by step resolution is over here.

elyor's user avatar

elyor

9589 silver badges19 bronze badges

answered Oct 4, 2018 at 9:44

Abhishek Galoda's user avatar

1

I was facing the same issue and get it resolved using the below simple steps:

1) Download the InstallCert.java from google

2) Compile it using javac InstallCert.java

3) Run InstallCert.java using java InstallCert.java, with the hostname and https port, and press “1” when asking for input. It will add the “localhost” as a trusted keystore, and generate a file named “jssecacerts“ as below:

java InstallCert localhost:443

4) copy the jssecacerts into $JAVA_HOME/jre/lib/security folder

Main source to resolve the issue here is:

https://ankurjain26.blogspot.in/2017/11/javaxnetsslsslhandshakeexception.html

ROMANIA_engineer's user avatar

answered Nov 6, 2017 at 16:20

Ankur jain's user avatar

Ankur jainAnkur jain

9333 gold badges14 silver badges21 bronze badges

1

Problem is, your eclipse is not able to connect the site which actually it is trying to.
I have faced similar issue and below given solution worked for me.

  1. Turn off any third party internet security application e.g. Zscaler
  2. Sometimes also need to disconnect VPN if you are connected.

Thanks

answered Jan 25, 2021 at 9:03

Aman Goel's user avatar

Aman GoelAman Goel

3,2211 gold badge21 silver badges17 bronze badges

0

Adding cacerts did not work for me.
After enabling log with flag -Djavax.net.debug=all, then came to know java reading from jssecacerts.

Import to jssecacerts worked finally.

answered Jul 14, 2017 at 10:31

alk453's user avatar

alk453alk453

1151 silver badge7 bronze badges

1

For me, certificate error popped up because I had fiddler running in background and that messes up with certificate. It acts as a proxy so close that and restart eclipse.

answered Jun 21, 2016 at 1:09

Atihska's user avatar

AtihskaAtihska

4,58510 gold badges50 silver badges94 bronze badges

3

I came across this question while trying to install the Cucumber-Eclipse plugin in Eclipse via their update site. I received the same SunCertPathBuilderException error:

Unable to read repository at http://cucumber.io/cucumber-eclipse/update-site/content.xml.
    Unable to read repository at http://cucumber.io/cucumber-eclipse/update-site/content.xml.
    sun.security.validator.ValidatorException: PKIX path building failed: 
   sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

While some of the other answers are appropriate and helpful for this question’s given situation, they were nevertheless unhelpful and misleading for my issue.

In my case, the issue was that the URL provided for their update site is:

https://cucumber.io/cucumber-eclipse/update-site

However when navigating to it via a browser, it redirected to (note the added «.github«):

http://cucumber.github.io/cucumber-eclipse/update-site/

So the resolution is to simply use the redirected version of the update site URL when adding the update site in eclipse.

answered May 1, 2017 at 21:07

royfripple's user avatar

royfrippleroyfripple

811 silver badge6 bronze badges

5

goals:

  1. use https connections
  2. verify SSL chains
  3. do not deal with cacerts
  4. add certificate in runtime
  5. do not lose certificates from cacerts

How to do it:

  1. define own keystore
  2. put certificate into keystore
  3. redefine SSL default context with our custom class
  4. ???
  5. profit

My Keystore wrapper file:

public class CertificateManager {

    private final static Logger logger = Logger.getLogger(CertificateManager.class);

    private String keyStoreLocation;
    private String keyStorePassword;
    private X509TrustManager myTrustManager;
    private static KeyStore myTrustStore;

    public CertificateManager(String keyStoreLocation, String keyStorePassword) throws Exception {
        this.keyStoreLocation = keyStoreLocation;
        this.keyStorePassword = keyStorePassword;
        myTrustStore = createKeyStore(keyStoreLocation, keyStorePassword);
    }

    public void addCustomCertificate(String certFileName, String certificateAlias)
            throws Exception {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        Certificate certificate = myTrustStore.getCertificate(certificateAlias);
        if (certificate == null) {
            logger.info("Certificate not exists");
            addCertificate(certFileName, certificateAlias);
        } else {
            logger.info("Certificate exists");
        }
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(myTrustStore);
        for (TrustManager tm : tmf.getTrustManagers()) {
            if (tm instanceof X509TrustManager) {
                setMytrustManager((X509TrustManager) tm);
                logger.info("Trust manager found");
                break;
            }
        }
    }

    private InputStream fullStream(String fname) throws IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream resource = classLoader.getResourceAsStream(fname);
        try {
            if (resource != null) {
                DataInputStream dis = new DataInputStream(resource);
                byte[] bytes = new byte[dis.available()];
                dis.readFully(bytes);
                return new ByteArrayInputStream(bytes);
            } else {
                logger.info("resource not found");
            }
        } catch (Exception e) {
            logger.error("exception in certificate fetching as resource", e);
        }
        return null;
    }

    public static KeyStore createKeyStore(String keystore, String pass) throws Exception {
        try {
            InputStream in = CertificateManager.class.getClass().getResourceAsStream(keystore);
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(in, pass.toCharArray());
            logger.info("Keystore was created from resource file");
            return keyStore;
        } catch (Exception e) {
            logger.info("Fail to create keystore from resource file");
        }

        File file = new File(keystore);
        KeyStore keyStore = KeyStore.getInstance("JKS");
        if (file.exists()) {
            keyStore.load(new FileInputStream(file), pass.toCharArray());
            logger.info("Default keystore loaded");
        } else {
            keyStore.load(null, null);
            keyStore.store(new FileOutputStream(file), pass.toCharArray());
            logger.info("New keystore created");
        }
        return keyStore;
    }

    private void addCertificate(String certFileName, String certificateAlias) throws CertificateException,
            IOException, KeyStoreException, NoSuchAlgorithmException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream certStream = fullStream(certFileName);
        Certificate certs = cf.generateCertificate(certStream);
        myTrustStore.setCertificateEntry(certificateAlias, certs);
        FileOutputStream out = new FileOutputStream(getKeyStoreLocation());
        myTrustStore.store(out, getKeyStorePassword().toCharArray());
        out.close();
        logger.info("Certificate pushed");
    }

    public String getKeyStoreLocation() {
        return keyStoreLocation;
    }

    public String getKeyStorePassword() {
        return keyStorePassword;
    }
    public X509TrustManager getMytrustManager() {
        return myTrustManager;
    }
    public void setMytrustManager(X509TrustManager myTrustManager) {
        this.myTrustManager = myTrustManager;
    }
}

This class will create keystore if necessary, and will be able to manage certificates inside of it. Now class for SSL context:

public class CustomTrustManager implements X509TrustManager {

    private final static Logger logger = Logger.getLogger(CertificateManager.class);

    private static SSLSocketFactory socketFactory;
    private static CustomTrustManager instance = new CustomTrustManager();
    private static List<CertificateManager> register = new ArrayList<>();

    public static CustomTrustManager getInstance() {
        return instance;
    }

    private X509TrustManager defaultTm;

    public void register(CertificateManager certificateManager) {
        for(CertificateManager manager : register) {
            if(manager == certificateManager) {
                logger.info("Certificate manager already registered");
                return;
            }
        }
        register.add(certificateManager);
        logger.info("New Certificate manager registered");
    }

    private CustomTrustManager() {
        try {
            String algorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);

            tmf.init((KeyStore) null);
            boolean found = false;
            for (TrustManager tm : tmf.getTrustManagers()) {
                if (tm instanceof X509TrustManager) {
                    defaultTm = (X509TrustManager) tm;
                    found = true;
                    break;
                }
            }
            if(found) {
                logger.info("Default trust manager found");
            } else {
                logger.warn("Default trust manager was not found");
            }

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{this}, null);
            SSLContext.setDefault(sslContext);
            socketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);


            logger.info("Custom trust manager was set");
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            logger.warn("Custom trust manager can't be set");
            e.printStackTrace();
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        List<X509Certificate> out = new ArrayList<>();
        if (defaultTm != null) {
            out.addAll(Arrays.asList(defaultTm.getAcceptedIssuers()));
        }
        int defaultCount = out.size();
        logger.info("Default trust manager contain " + defaultCount + " certficates");
        for(CertificateManager manager : register) {
            X509TrustManager customTrustManager = manager.getMytrustManager();
            X509Certificate[] issuers = customTrustManager.getAcceptedIssuers();
            out.addAll(Arrays.asList(issuers));
        }
        logger.info("Custom trust managers contain " + (out.size() - defaultCount) + " certficates");
        X509Certificate[] arrayOut = new X509Certificate[out.size()];
        return out.toArray(arrayOut);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
        for(CertificateManager certificateManager : register) {
            X509TrustManager customTrustManager = certificateManager.getMytrustManager();
            try {
                customTrustManager.checkServerTrusted(chain, authType);
                logger.info("Certificate chain (server) was aproved by custom trust manager");
                return;
            } catch (Exception e) {
            }
        }
        if (defaultTm != null) {
            defaultTm.checkServerTrusted(chain, authType);
            logger.info("Certificate chain (server) was aproved by default trust manager");
        } else {
            logger.info("Certificate chain (server) was rejected");
            throw new CertificateException("Can't check server trusted certificate.");
        }
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
        try {
            if (defaultTm != null) {
                defaultTm.checkClientTrusted(chain, authType);
                logger.info("Certificate chain (client) was aproved by default trust manager");
            } else {
                throw new NullPointerException();
            }
        } catch (Exception e) {
            for(CertificateManager certificateManager : register) {
                X509TrustManager customTrustManager = certificateManager.getMytrustManager();
                try {
                    customTrustManager.checkClientTrusted(chain, authType);
                    logger.info("Certificate chain (client) was aproved by custom trust manager");
                    return;
                } catch (Exception e1) {
                }
            }
            logger.info("Certificate chain (client) was rejected");
            throw new CertificateException("Can't check client trusted certificate.");
        }
    }

    public SSLSocketFactory getSocketFactory() {
        return socketFactory;
    }
}

This class made as singleton, because only one defaultSSL context allowed. So, now usage:

            CertificateManager certificateManager = new CertificateManager("C:\myapplication\mykeystore.jks", "changeit");
            String certificatePath = "C:\myapplication\public_key_for_your_ssl_service.crt";
            try {
                certificateManager.addCustomCertificate(certificatePath, "alias_for_public_key_for_your_ssl_service");
            } catch (Exception e) {
                log.error("Can't add custom certificate");
                e.printStackTrace();
            }
            CustomTrustManager.getInstance().register(certificateManager);

Possibly, it will not work with this settings, because I keep certificate file inside of resource folder, so my path is not absolute. But generally, it work perfectly.

answered Aug 24, 2017 at 11:56

degr's user avatar

degrdegr

1,5491 gold badge18 silver badges36 bronze badges

1

If your repository URL also work on HTTP and the security is not a concern, you can go to settings.xml (often, but not always, located in %USERPROFILE%/.m2) and replace HTTPS with HTTP for <repository> and <pluginRepository> URLs.

For example, this:

<repository>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
    <id>central</id>
    <name>libs-release</name>
    <url>https://<artifactory>/libs-release</url>
</repository>

should be replaced by this:

<repository>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
    <id>central</id>
    <name>libs-release</name>
    <url>https://<artifactory>/libs-release</url>
</repository>

answered Nov 14, 2018 at 8:23

ROMANIA_engineer's user avatar

ROMANIA_engineerROMANIA_engineer

53k28 gold badges199 silver badges194 bronze badges

1

I was using my own trust store rather than JRE one by passing arg -Djavax.net.ssl.trustStore=

I was getting this error regardless of certs in truststore. The issue for me was the ordering of of the properties passed on arg line.
When i put -Djavax.net.ssl.trustStore=& -Djavax.net.ssl.trustStorePassword= before -Dspring.config.location= & -jar args i was able to successfully invoke my rest call over https.

answered Feb 18, 2019 at 8:16

jasonoriordan's user avatar

1

I solved this issue on Windows Server 2016 with Java 8, by importing cert from pkcs12 store to cacerts keystore.

Path to pkcs12 store:

C:Appspkcs12.pfx

Path to Java cacerts:

C:Program FilesJavajre1.8.0_151libsecuritycacerts

Path to keytool:

C:Program FilesJavajre1.8.0_151bin

After possitioning to folder with keytool in command prompt (as administrator), command to import cert from pkcs12 to cacerts is as follows:

keytool -v -importkeystore -srckeystore C:Appspkcs12.pfx -srcstoretype PKCS12 -destkeystore "C:Program FilesJavajre1.8.0_151libsecuritycacerts" -deststoretype JKS

You will be prompted to:
1. enter destination keystore password (cacerts pasword, default is «changeit»)
2. enter source keystore password (pkcs12 password)

For changes to take effect, restart server machine (or just restart JVM).

answered Dec 18, 2019 at 15:05

ognjenkl's user avatar

ognjenklognjenkl

1,28912 silver badges10 bronze badges

2

I ran into same issue but updating wrong jre on my linux machine. It is highly likely that tomcat is using different jre and your cli prompt is configured to use a different jre.

Make sure you are picking up the correct jre.

Step #1:

ps -ef | grep tomcat

You will see some thing like:

root     29855     1  3 17:54 pts/3    00:00:42 /usr/java/jdk1.7.0_79/jre/bin/java 

Now use this:

keytool -import -alias example -keystore  /usr/java/jdk1.7.0_79/jre/lib/security/cacerts -file cert.cer
PWD: changeit

*.cer file can be geneated as shown below: (or you can use your own)

openssl x509 -in cert.pem -outform pem -outform der -out cert.cer

Aplet123's user avatar

Aplet123

32.8k1 gold badge28 silver badges54 bronze badges

answered May 21, 2020 at 1:18

Ammad's user avatar

AmmadAmmad

3,91511 gold badges34 silver badges59 bronze badges

If you are still getting this error

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid 
certification path to requested target

after executing the below command and restarting the java process

keytool -import -alias certificatealias -keystore C:Program FilesJavajre1.8.0_151libsecuritycacerts -file certificate.cer

Then there is some issue in JDK. Try to install JDK from a trusted provider.
Once you reinstalled it from trusted provider you won’t face this issue.

answered Feb 26, 2021 at 12:22

GnanaJeyam's user avatar

GnanaJeyamGnanaJeyam

2,67616 silver badges27 bronze badges

1

In case your host sits behind firewall/proxy , use following command in cmd:

keytool -J-Dhttps.proxyHost=<proxy_hostname> -J-Dhttps.proxyPort=<proxy_port> -printcert -rfc -sslserver <remote_host_name:remote_ssl_port>

Replace <proxy_hostname> and <proxy_port> with the HTTP proxy server that is configured. Replace <remote_host_name:remote_ssl_port> with one of the remote host (basically url) and port having the certification problem.

Take the last certificate content printed and copy it (also copy begin and end certificate). Paste it in text file and give .crt extension to it . Now import this certificate to cacerts using java keytool command and it should work .

keytool -importcert -file <filename>.crt -alias randomaliasname -keystore %JAVA_HOME%/jre/lib/security/cacerts -storepass changeit

answered May 15, 2019 at 15:16

A W's user avatar

A WA W

93110 silver badges18 bronze badges

1

1-First of all, import you’r crt file into {JAVA_HOME}/jre/security/cacerts, if you still faced with this exception, change you’r jdk version. For example from jdk1.8.0_17 to jdk1.8.0_231

answered Feb 2, 2021 at 12:26

Tohid Makari's user avatar

Tohid MakariTohid Makari

1,3722 gold badges11 silver badges27 bronze badges

I was facing this issue with Java 8 but it got solved after upgrading to Java 11

answered Jan 22, 2022 at 11:31

Shadaksharayya H A's user avatar

Here normally this kind of exception occurs when there is mismatch in the PATH of trusted certificate. Check the configuration or path where this server certificate is required for secured communication.

answered Jan 12, 2014 at 19:32

ketan's user avatar

ketanketan

12 bronze badges

3


4 Flares



Twitter


1








Facebook


1








Google+


2








LinkedIn


0








Email









Filament.io






4 Flares


×

How To Fix Error : sun.security.validator.ValidatorException: PKIX path building failed:

sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

You could get the error “PKIX path building failed” validation error when working on a client that works with an SSL enabled server running in https protocol. This article focuses on detecting the root cause of the error and on how to fix the issue.
There are other similar issues related the SSL certificates. One of the common situation is the missing certificate in trust store. In that case you may see the following error message.

Caused by: java.security.cert.CertificateException: No name matching localhost found at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:210) at sun.security.util.HostnameChecker.match(HostnameChecker.java:77)

See the following article to read more about the above error and its solution.

    How to Fix : java.security.cert.CertificateException: No name matching localhost found

Table of Contents

  • What is PKIX?
  • How to Detect PKIX Path Building Failed Error?
  • Unable to Find Valid Certification Path to Requested Target: Possible Reason For The Error
  • Fix for PKIX path building failed Error:sun.security.provider.certpath.SunCertPathBuilderException
  • References

The first part of the error, “javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: “,  indicates the type of error and the second part of the error message “sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target” gives an indication on what exactly went wrong.
Before diving into the cause and solution let us get some general knowledge 🙂
java pkix path building validation

What is PKIX?

PKIX is Public-Key Infrastructure X.509. PKIX is public key infrastructure standards based on X.509 protocol. X.509 is an ITU-T cryptography standard for a public key infrastructure (PKI) and Privilege Management Infrastructure (PMI). Read references for more details on The PKIX (Public-Key Infrastructure X.509) Working Group (PKIX-WG).

PKIX path building failed : sun.security.validator.ValidatorException

This error is one of the many SSL related errors you may experience when you start developing applications those communicates securely. This happens during one of the SSL Handshake phase. This exception is of type javax.net.ssl.SSLHandshakeException,  which indicates that the client and server could not negotiate the desired level of security. The connection is no longer usable.
The complete exception message is below:

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

How to Detect PKIX Path Building Failed Error?

Even though this is a common exception while connecting a service over HTTPS,  identifying the exact problem without proper debugging configuration is difficult. Unless you enable the SSL handshake debug mode (Java VM parameter -Djavax.net.debug=ssl:handshake) you will not be able to identify the root cause. Without SSL debug enabled you most likely will see the following error.

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:352)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:572)

The above message is more generic and in most cases will not give you the root cause of the issue. Once you enable SSL handshake debug mode you will see the following exception trace:

 http-localhost/127.0.0.1:8443-1, SEND TLSv1 ALERT: fatal, description = certificate_unknown
http-localhost/127.0.0.1:8443-1, WRITE: TLSv1 Alert, length = 2
http-localhost/127.0.0.1:8443-1, called closeSocket()
http-localhost/127.0.0.1:8443-1, 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
http-localhost/127.0.0.1:8443-1, called close()
http-localhost/127.0.0.1:8443-1, called closeInternal(true)

The above error indicates a missing trusted certificate in the trusted Java  store. Some other cases where,  you already have the certificate but there is a problem with its validity, you may see the following error (“timestamp check failed“).

handling exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed.

We will be addressing the first scenario in which there is no certificate available (certificate_unknown).

Unable to Find Valid Certification Path to Requested Target: Possible Reason For The Error

If we look at the phase of the SSL handshake we’re in, we can see that we’ve already sent our client certificate and finishing up the handshake when we receive this error.

2015-02-04 21:59:33,002 INFO  [stdout] (http-localhost/127.0.0.1:8443-2) -  - *** ServerHelloDone
http-localhost/127.0.0.1:8443-2, WRITE: TLSv1 Handshake, length = 865
http-localhost/127.0.0.1:8443-1, READ: TLSv1 Handshake, length = 865
*** ServerHello, TLSv1
RandomCookie:  GMT: 1406265764 bytes = { 30, 87, 196, 168, 159, 159, 7, 254, 62, 168, 199, 80, 108, 117, 48, 3, 113, 72, 1, 226, 31, 195, 238, 86, 88, 192, 96, 94 }
Session ID:  {84, 210, 234, 164, 204, 121, 25, 56, 166, 145, 81, 180, 26, 103, 98, 72, 207, 54, 246, 139, 136, 17, 1, 140, 50, 131, 195, 18, 157, 80, 142, 4}
Cipher Suite: SSL_RSA_WITH_RC4_128_MD5
Compression Method: 0
Extension renegotiation_info, renegotiated_connection: 
***
%% Created:  [Session-9, SSL_RSA_WITH_RC4_128_MD5]
** SSL_RSA_WITH_RC4_128_MD5
*** Certificate chain
Version: V3
Subject: CN=************************************
Signature Algorithm: SHA1withRSA, OID = *********************
Key:  Sun RSA public key, 2048 bits
.................................................
...................................................
***
SEND TLSv1 ALERT:  fatal, description = certificate_unknown
WRITE: TLSv1 Alert, length = 2
READ: TLSv1 Alert, length = 2
called closeSocket()
RECV TLSv1 ALERT:  fatal, certificate_unknown
called closeSocket()
handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
handling exception: 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

The above error stack trace is actually helpful. It says that “unable to find valid certification path to requested target“. This means that the certificate the server certificate is not issued by certification authority, but a self signed or issued by a private CMS. If the certificate is issued by a trusted authority (VeriSign etc) the error will not happen.

Fix for PKIX path building failed Error:sun.security.provider.certpath.SunCertPathBuilderException

All you need to do to fix this error is to add the server certificate to your trusted Java key store. First You need to download the document from the server.

To download: access the URL of the service from any browser.You will get a certificate related warning message. Click on view certificate and then Install certificate. You can export the certificate from browser to some location in hard drive (In IE go to Tools->’Internet Options’ ->Content->Certificates).

Once you have the certificate in your hard drive you can import it to the Java trust store. To import the certificate to the trusted Java key store, you can use the java ‘keytool‘ tool.
Use keytool command as follows to import the certificate to JRE.

keytool -import -alias _alias_name_ -keystore ..libsecuritycacerts -file _path_to_cer_file

It will ask for a password. By default the password is “changeit”. If the password is different you may not be able to import the certificate.
Note: You can also use the installcert java program from here.
Once completed restart/re-run your client application. You will be able to see successful SSL handshakes.

References:

  1. X.509 Public-key and attribute certificate frameworks
  2. Internet X.509 Public Key Infrastructure Certificate and CRL Profile RFC 2459
  3. Import the Certificate as a Trusted Certificate 

Incoming search terms:

  • pkix path building failed
  • pkix validation failed
  • PKIXPathBuildingFailed(Validation):sun security validator ValidatorException
  • sun security validator ValidatorException: PKIX path building failed: sun security provider certpath SunCertPathBuilderException: unable to find valid certification path to requested target
  • https://java globinch com/enterprise-java/security/pkix-path-building-failed-validation-sun-security-validatorexception/
  • PKIX path building failed: sun security provider certpath SunCertPathBuilderException: unable to find valid certification path to requested target
  • feign RetryableException: PKIX path building failed: sun security provider certpath SunCertPathBuilderException:
  • pkix path validation failed: java security cert certpathvalidatorexception: validity check failed
  • dbviewer download driver javax net ssl SSLHandshakeException:PKIX
  • Couldnt download vanilla jar! sun security validator ValidatorException: PKIX path building failed: sun security provider certpath SunCertPathBuilderException: unable to find valid certification path to requested target


4 Flares



Twitter


1








Facebook


1








Google+


2








LinkedIn


0








Email









Filament.io






4 Flares


×

The article presents the steps to import required certificates and enable Java application to connect to Azure SQL DB/Managed Instance. If required certificates are missing on client machine when connecting via AAD authentication, a similar error will be prompted in the application logs:

«SQLServerException: Failed to authenticate the user in Active Directory (Authentication=ActiveDirectoryPassword).
Caused by: ExecutionException: mssql_shaded.com.microsoft.aad.adal4j.AuthenticationException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Caused by: AuthenticationException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. «

This is an issue in Java Certificate Store. As a quick workaround, if you enable TrustServerCertificate=True in the connection string, the connection from JDBC succeeds. When TrustServerCertificate is set to true, the transport layer will use SSL to encrypt the channel and bypass walking the certificate chain to validate trust. If TrustServerCertificate is set to true and encryption is turned on, the encryption level specified on the server will be used even if Encrypt is set to false. The connection will fail otherwise. However, for security considerations, it is not recommended to bypass the certificate validation. Hence, to address the issue, follow the steps below to change the connection string and import the required certificates. 

  • Change the connection string to point to the Java certificate path

    String connectionUrl =  «jdbc:sqlserver://localhost:1433;» + 
        «databaseName=AdventureWorks;integratedSecurity=true;» + 
        «encrypt=true; trustServerCertificate=false;» + 
        «trustStore= C:Program FilesJavajdk-14.0.2libcacert;trustStorePassword=changeit»;

  • Import all the certificates mentioned in this document.

    Note: To import above certificates into the keystore cacerts, please use below command and please note you must mention truststore and truststore password in the connection string to successfully connect.  

Steps to import missing certificates in Java Certificate Store

Download all the certs from here, store them in a location on client host and then use keytool utility to import these certificates into the truststore. Please follow the below steps:

  • Save all the certificates from the above MS doc.
  • Keytool utility is in the bin folder of your default Java location (C:Program FilesJavajdk-14.0.2bin). You need to use command prompt to navigate to that location.
  • Then you can use the keytool command to import the certificate previously saved. 
  • When prompted for password insert the key in the password as “changeit

Example of commands:

keytool -importcert -trustcacerts -alias TLS1 -file «C:UsersDocumentsMicrosoft RSA TLS CA 01.crt» -keystore «C:Program FilesJavajdk-14.0.2libsecuritycacerts»

keytool -importcert -trustcacerts -alias TLS2 -file «C:UsersDocumentsMicrosoft RSA TLS CA 02.crt» -keystore «C:Program FilesJavajdk-14.0.2libsecuritycacerts»

Certificate was added to keystore.

The problem

It may happen to you that when you try and pull some Java dependencies, you will get the annoying PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target error.

It may look something like this:

Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.4.0 from/to tpvr-ibm (https://nexus-***.***.***.***:8081/nexus/content/repositories/tpvr-ibm): PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

The solution (recommended)

  1. Go to URL in your browser:
    • firefox – click on HTTPS certificate chain (the lock icon right next to URL address). Click "more info" > "security" > "show certificate" > "details" > "export..". Pickup the name and choose file type example.cer
    • chrome – click on site icon left to address in address bar, select “Certificate” -> “Details” -> “Export” and save in format “Der-encoded binary, single certificate”.
  2. Now you have file with keystore and you have to add it to your JVM. Determine location of cacerts files
    • Windows: C:Program Files (x86)Javajre1.8.0_22libsecuritycacerts
    • Mac: /Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home/jre/lib/security/cacerts
  3. Next import the example.cer file into cacerts in command line:

What commands to run

Navigate to the security path:

cd /Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home/jre/lib/security

Run the keytool and import the certificate file into the cacerts store:

keytool -import -alias example -keystore cacerts -file /path/to/example.cer

You will be asked for password which default is changeit

Restart your JVM/PC.

keytool -trustcacerts -keystore "%JAVA_HOME%jrelibsecuritycacerts" -storepass changeit -importcert -alias <alias_name> -file <path_to_crt_file>

Some other things you can follow

  • copy a valid cacerts file from the Oracle or any other vendors’ JDK into the $JAVA_HOME/lib/security/
  • copy a valid cacerts file from the Oracle or any other vendors’ JRE into the $JAVA_HOME/jre/lib/security/

An alternative solution (development)

As an alternative, you can simply disable SSL validation.

Make sure to only do this while in development mode. Doing this in production is not recommended is unsafe.

-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true

The above are two command-line arguments to turn SSL off at runtime.

Author: Abhishek Bathwal

While developing some application, we might sometimes come across below error which the maven throws while building the application:

Reason: The error due to the system firewall. The system firewall restricts the application to connect to external unsecured systems. The firewall requires a valid certificate to allow access to the external systems.

Solution: The solution is very simple. We just need to install the required certificates of the external system in our system so the firewall allows us to interact with the external system and complete our process.

We are going to perform two activities:

  1. Download the Certificate.
  2. Install the Certificate.

To download the certificate, follow the below steps:

  1. Take the particular URL from the error and copy it to a browser (In the above error the url is https://repository.mulesoft.org/releases/).

  1. Now to the left of the URL there is a lock icon (). Click on this icon and a window will pop up. From the window, select the certificate.

  1. Once we select the certificate, it will redirect to another window. From there we have to select the Details tab and from the Details click on Copy to File. After clicking again, a new window will pop up. In that window, select next.

  1. After we perform all the above steps, we will be redirected to a new window where we need to select the format for the certificate. We will have to choose DER encoded binary and click on Next.

  1. Now we need to choose a location where we need to save the certificate and we also need to give some name to the certificate.

  1. Once a File name is given and saved, then select Next. It will direct us to another window showing the details. If all the details are correct, click on Finish. A export Success pop up will appear.

Note: I saved the File name as repo.

So, the downloading of certificates is done. Now the next process is to install the certificate in the cacerts file of the jdk installed in our system using the command line.

Installation of the Certificate from Command line:

Command for installation: keytool -importcert -trustcacerts -alias <alias name for the certificate> -file <path were we have save the certificate> -keystore “<path for the cacerts file>” -storepass changeit

For me the Command will be: keytool -importcert -trustcacerts -alias repo -file C:UsersDELLDesktoprepo.cer -keystore “C:Program FilesJavajdk1.8.0_131jrelibsecuritycarcets” -storepass changeit

Note

  1. I am using jdk1.8.0_131 so the cacerts file path for my system is “C:Program FilesJavajdk1.8.0_131jrelibsecuritycarcets”. It may differ for you based on your system and jdk version.
  2. I have given the alias name as repo and the path where I save my certificate is C:UsersDELLDesktoprepo.cer
To install the certificate, follow the below steps:
  1. Open Command Prompt as an Administrator and use the command for installation and press enter.

  1. Once the command is executed, it will ask for confirmation. Write Yes and the certificate will be installed with confirmation.

In the above process, we have downloaded and installed the certificate successfully in our system.

Now if we will execute the application it will not show certificate issues and will also download the required data from that particular system.

Thank you!

Когда люди говорят «API тесты«, они обычно имеют в виду API, предоставляемый поверх протоколов HTTP либо HTTPs. Так сложилось, что упомянутые протоколы в подавляющем большинстве случаев используются при реализации архитектуры REST, а также, для реализации веб-сервисов, работающих по протоколу SOAP. В то время как простой HTTP обычно не вызывает никаких проблем, его ssl-расширение требует более сложного подхода и привлечения таких артефактов как «ключи» и «сертификаты». Некорректная конфигурация соединения в таких случаях часто приводит к падениям тестов в результате невозможности проверить валидность сертификата, возвращаемого тестовым сервером. В этой статье мы взглянем на такую проблему и узнаем как её решать.

Возможно вы видели сообщение об ошибке вида «PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target». Если да, значит вы нашли нужную статью.

В нашем примере мы создадим вызов ендпоинта «https://webelement.click», используя базовый инструментарий, входящий в поставку Java SDK (пакет java.net.*). Этот вызов скорее всего не будет успешным по причине невозможности валидации предоставляемого сервером сертификата. После этого мы сконфигурируем наш кастомный trust store (чуть позже я объясню что это такое) и научим наш код его использовать. Также мы рассмотрим подход при котором созданный нами trust store станет частью нашего тестового проекта, что сделает тесты более независимыми от среды исполнения.

Итак, вот модель наших API-тестов, которые пытаются осуществить вызов ендпоинта с использованием Secure Socket Layer (также известным под именем Transport Layer Security) протокола.

package click.webelement.https;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiWithSSL {

    public static void main(String[] args) {

        try {
            HttpURLConnection connection = (HttpURLConnection) new URL("https://webelement.click").openConnection();
            int responseCode = connection.getResponseCode();
            if(responseCode != 200){
                System.out.println("Test failed with actual status code: " + responseCode);
            }else{
                System.out.println("Test passed");
            }
        } catch (IOException e) {
            System.out.println("Test failed with exception: " + e.getMessage());

        }

    }

}

Предполагается, что тест выше упадёт. Давайте теперь заглянем в проблему чуть глубже.

Вообще, конечно, может случиться и так, что тест из примера пройдет успешно. Это произойдет в том случае, если ваша среда корректно настроена и хранилище доверенных сертификатов, используемое по умолчанию содержит сертификаты агентства, выпускающего сертификаты LetsEncrypt. C другой стороны, если бы у вас не было бы проблем, вы бы вряд ли искали решение, правда?

Чаще всего рассматриваемая проблема возникает, когда вы имеете дело с сертификатами, выпущенными локальными корпоративными сертификационными центрами.

В любом случае, я рекомендую дочитать эту статью до конца для того чтобы получить более ясное понимание того, почему вы можете столкнуться с проблемой валидации сертификата. Я также рекомендую изменить URL используемого ендпоинта на ваш вариант с которым вы испытываете проблемы.

Что вообще означает фраза «PKIX path building failed»?

Когда ваш код пытается обратиться к https-эндпоинту, удаленный сервер посылает вашему клиенту свой публичный ключ и сертификат, подтверждающий его (сервера) «личность». Клиенту, в свою очередь, необходимо решить может ли он доверять такому сертификату. Каждый сертификат подписан цифровой подписью издателя (третьей стороной), что означает, что проверить такую подпись возможно только с помощью публичного ключа издателя.

Но можем ли мы доверять издателю этого сертификата (третьей стороне процесса)? Публичный ключ издателя также сопровождается своим сертификатом, который может быть проверен идентичным путем. Такая цепочка имеет название certificate chain.

В чем состоит основная идея, лежащая в основе протокола https? Этот протокол использует т.н. криптографию открытого ключа (так же известную как «асимметричная» криптография) для того чтобы согласовать с сервером «симметричный» ключ (а фактически — пароль, при помощи которого будут кодироваться и декодироваться сообщения). Таким образом, на первом этапе взаимодействия, клиенту требуется публичный ключ сервера, чтобы при помощи него зашифровать сообщения фазы упомянутого согласования.

Для того чтобы клиент мог быть уверенным в том, что он действительно общается с сервером, с которым он думает, что общается, публичный ключ обычно сопровождается сертификатом. Сертификат — это такой документ, который содержит имя субъекта, а также публичный ключ, ассоциированный с именем субъекта. На основании всей информация сертификата, вычисляется хэш-строка, которая затем подписывается (шифруется) при помощи секретного ключа сертификационного агентства (CA), выдавшего данный сертификат. Единственным способом проверить валидность такого сертификата является вычисление хэш-строки сертификата и сравнение результата с расшифрованным «подписанным» хэшем. Успешно расшифровать подписанный хэш можно только при помощи публичного ключа агенства, который в свою очередь, также сопровождается своим сертификатом.

Любая реализация протоколов HTTPs/SSL подразумевает наличие некоего хранилища сертификатов, которые считаются «доверенными» (в англоязычной среде такое хранилище называется trust store). Таким сертификатам мы доверяем по умолчанию. Вообще говоря, таких хранилищ может быть несколько, и каждое может быть использовано для своих целей. Основное правило, которое необходимо соблюсти для успешной коммуникации вашего кода и HTTPs-сервиса — это наличие хотя бы одного сертификата из цепочки в доверенном хранилище. В Java (в том случае если вы не меняли дефолтное состояние вещей), доверенное хранилище находится в файле %JRE_HOME%/lib/security/cacerts. Для большинства Java дистрибутивов, такой trust store уже содержит сертификаты/ключи всех общеизвестных сертификационных агентств, так что у вас не должно будет возникнуть проблем при соединении с большинством публичных сервисов в Интернете. Однако, для интранет-сервисов дела обстоят не так безоблачно.

Сообщение «PKIX path building failed» означает, что ssl-библиотека Java в процессе валидации цепочки сертификатов, пришедшей с сервера не смогла обнаружить такой сертификат, который бы находился в используемом trust store.

Подготавливаем траст стор для того чтобы наш код доверял бы сертификату от тестового сервера

Мы собираемся применить комплексный подход к решению нашей задачи. Сперва нам необходимо подготовить доверенное хранилище, которое бы содержало сертификат, возвращаемый нашим тестовым сервером. Ниже перечислены шаги, которые необходимо выполнить:

  1. Получить файл сертификата, содержащий сертификат вашего сервиса. Это может быть сделано одним из двух способов. 1) спросить ваших разработчиков или девопсов, ответственных за имплементацию и деплоймент сервиса. 2) Открыть https ендпоинт в вашем веб-браузере, кликнуть на иконку «замочек» рядом с адресной строкой, следовать указаниям открывшегося диалога, который в итоге приведет вас к ссылке на экспортирование сертификата в виде файла. Нам подойдут сертификаты в форматах .pem или .cer.

  2. Создать какой-нибудь каталог, куда положить полученный файл. Открыть командную строку и перейти в созданный каталог. Важно убедиться в том, что ваша переменная окружения PATH содержит каталог %JRE_HOME%/bin (это необходимо для того, чтобы иметь возможность запускать утилиту keytool из любого места вашей файловой системы).

  3. Находясь в созданном каталоге, импортируйте файл сертификата в хранилище (которое пока еще не создано) используя следующую команду.

keytool -importcert -file your-cert-file.pem -keystore mytruststore -storetype PKCS12

Установите какой-нибудь пароль. Этот пароль будет использоваться при обращении вашего кода к созданному хранилищу. Также ответьте «Yes» на вопрос действительно ли вы хотите доверять импортируемому сертификату.

После того как импорт завершится вы должны будете увидеть новый файл mytruststore в каталоге с сертификатом. Этот файл — и есть ваше новое доверенное хранилище сертификатов, которое теперь содержит сертификат, возвращаемый вашим тестовым сервисом.

Как использовать новый trust store в моем Java-тесте?

После того, как мы создали новый траст стор, нам необходимо как-то сообщить нашему тестовому коду, что теперь ему следует работать с новым хранилищем. Это можно сделать либо установив значения для соответствующих системных свойств через параметры командной строки при вызове ваших тестов из консоли (это, например, удобно делать при интеграции ваших тестов с инструментами Continuous Integration) или установить эти значения прямо в исполняемом коде. Мы будем использовать второй способ. Свойства, значения для которых нам надо будет установить, такие: javax.net.ssl.trustStore and javax.net.ssl.trustStorePassword.

Предположим, что мы создали хранилище доверенных сертификатов в файле mytruststore, который находится в каталоге /home/me/ssl и пароль, установленный для нашего хранилища — mystorepass. Тогда неработающий пример из начала статьи можно было бы переписать таким образом:

package click.webelement.https;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiWithSSL {

    static {

        System.setProperty("javax.net.ssl.trustStore", "/home/me/ssl/mytruststore");
        System.setProperty("javax.net.ssl.trustStorePassword", "mystorepass");

    }

    public static void main(String[] args) {

        try {
            HttpURLConnection connection = (HttpURLConnection) new URL("https://webelement.click").openConnection();
            int responseCode = connection.getResponseCode();
            if(responseCode != 200){
                System.out.println("Test failed with actual status code: " + responseCode);
            }else{
                System.out.println("Test passed");
            }
        } catch (IOException e) {
            System.out.println("Test failed with exception: " + e.getMessage());
        }

    }

}

Где мы просто добавляем блок статической инициализации в котором устанавливаем необходимые значения для наших свойств.

Такая настройка не обязательно должна находится в блоке статической инициализации. Она может быть добавлена в любое место, исполняемое до вызова https ендпоинта.

В моей следующей статье, вы узнаете как сделать доверенное хранилище сертификатов частью тестового проекта, таким образом, что оно будет распространяться вместе с тестовым кодом и использоваться в неизменном виде где бы ваши тесты не запускались. Такой подход потребует некоего стандарта подхода к формированию структуры тестовго проекта. В частности, использование таких фреймворков как Maven и JUnit.

Если после прочтения у вас всё ещё остались вопросы, присылайте их мне используя эту форму обратной связи. Я постараюсь ответить вам напрямую, а также скорректировать статью, опираясь на ваши отзывы.

Reading Time: 3 minutes

In this blog, we learn how to resolve PKIX path-building Issue.
While developing some application, we might sometimes come across the below error which the maven throws while building the application:

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

Reason

  • The error is due to the system firewall. The system firewall restricts the application to connect to external unsecured systems. The firewall requires a valid certificate to allow access to the external systems.

Cause

  • Whenever Java attempts to connect to another application over SSL (e.g.: HTTPS, IMAPS, LDAPS) then it will only be able to connect to that application if it can trust it. The way trust is handled in the Java world is that you have a Keystore, also known as the trust store. This contains a list of all known Certificate Authority (CA) certificates. Java will only trust certificates.

Resolution

  • The solution is very simple. We just need to install the required certificates of the external system in our system so the firewall allows us to interact with the external system and complete our process.
    • We are going to perform two activities:
      • Download the Certificate.
      • Install the Certificate.

To download the certificate, follow the below steps:

  • Take the particular URL from the error and copy it to a browser (In the above error the URL).
  • Now to the left of the URL, there is a lock icon (). Click on this icon and a window will pop up. From the window, select the certificate.
  • Once we select the certificate, it will redirect to another window. From there we have to select the Details tab and from the Details click on Copy to File. After clicking again, a new window will pop up. In that window, select next.
  • After we perform all the above steps, we will be redirected to a new window where we need to select the format for the certificate. We will have to choose DER encoded binary and click on Next.
  • Now we need to choose a location where we need to save the certificate and we also need to give some name to the certificate.
  • Once a File name is given and saved, then select Next. It will direct us to another window showing the details. If all the details are correct, click on Finish. A export Success pop up will appear.

So, the downloading of certificates is done. Now the next process is to install the certificate in the cacerts file of the jdk installed in our system using the command line.

Installation of the Certificate from Command line:

  • Go to the JDK security folder.
  • Command for installation: keytool -importcert -alias <alias name for the certificate> -file <path were we have save the certificate> –keystore cacerts
  • For me the Command will be in Window: keytool -importcert -alias cer10 -file C:UsersprajjawalkDocumentscercer10.cer -keystore cacerts
  • For me the Command will be in Ubuntu: sudo keytool -importcert -alias cer10 -file /mnt/c/Users/prajjawalk/Documents/cer/cer10.cer -keystore cacert

Note: 

For Window :

  • I am using openjdk 11.0.11 so the cacerts file path for my system is C:Program FilesJavajdk-11.0.11libsecuritycacerts. It may differ for you based on your system and jdk version.
  • I have given the alias name as cer10 and the path where I save my certificate is C:UsersprajjawalkDocumentscercer10.cer

For Ubuntu :

  • I am using openjdk 11.0.11 so the cacerts file path for my system is /usr/lib/jvm/java-11-openjdk-amd64/lib/security$. It may differ for you based on your system and jdk version.
  • I have given the alias name as cer10 and the path where I save my certificate is  /mnt/c/Users/prajjawalk/Documents/cer/cer10.cer

To install the certificate, follow the below steps:

  • Open Command Prompt as an Administrator and use the command for installation and press enter.
  • Enter the Password – changeit
  • Once the command is executed, it will ask for confirmation. Write Yes and the certificate will be install with confirmation.

In the above process, we have downloaded and installed the certificate successfully in our system.

Now if we will execute the application it will not show certificate issues and will also download the required data from that particular system.

Knoldus-blog-footer-image

Понравилась статья? Поделить с друзьями:
  • Error build identity info does not contain a macosvariant
  • Error build dso 113 death stranding
  • Error build command phasescriptexecution failed with a nonzero exit code
  • Error build command cmake not foundfailure running cmake
  • Error buffer was not allocated stalker