Keytool error java lang exception input not an x 509 certificate

In step 1 of probe for email document for TLS connectionhttps://www.ibm.com/support/knowledgecenter/SSSHTQ/omnibus/probes/email/wip/reference/email_keystore_file.htmlthe commandkeytool -import -alias client_certificate -file certificate_file -keystore keystore_namegive error of "java.lang.Exception: Input not an X.509 certificate"

Problem

In step 1 of probe for email document for TLS connection

https://www.ibm.com/support/knowledgecenter/SSSHTQ/omnibus/probes/email/wip/reference/email_keystore_file.html

the command

keytool -import -alias client_certificate -file certificate_file -keystore keystore_name

give error of «java.lang.Exception: Input not an X.509 certificate»

Cause

A wrong certificate type was used.

A version of .cer certificate is expected. Using a certificate of .p7b will give the error.

Diagnosing The Problem

Check to make sure the certificate used is of .cer type.

Resolving The Problem

Convert the .p7b certificate file to x.509 (.cer) certificate file using Microsoft Windows

  1. Copy the  .p7b certificate file to a Windows desktop
  2. Rename the PKCS 7 certificate and give it a .p7b extension if need to.
  3. Open the .p7b file
  4. Click the plus ( + ) symbol
  5. Click the Certificates directory
  6. Right click on your certificate file
  7. Select All Tasks > Export
  8. Click Next
  9. Select Base-64 encoded X.509 (.cer) > Click Next
  10. Browse to a location to store the file
  11. Enter a File name. For example MyCert. The .cer extension is added automatically
  12. Click Save
  13. Click Next
  14. Click Finish

Alternatively use openssl

openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer

Used the converted .cer certificate to import into your keystore.

Document Location

Worldwide

[{«Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Product»:{«code»:»SSSHTQ»,»label»:»Tivoli Netcool/OMNIbus»},»Component»:»Probe for Email»,»Platform»:[{«code»:»PF025″,»label»:»Platform Independent»}],»Version»:»All Versions»,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]

Historical Number

TS002639718

Product Synonym

email probe

This Article consists of advanced troubleshooting to a very problematic issue that comes up with versions of Keytool when installing an SSL certificate. There can be numerous causes for this issue.

By all normal means when following SSL Installation Instructions for Tomcat using pkcs7 or SSL Installation Instructions for Tomcat using x.509 the user should have a smooth installation, but user may receive the following error message.

Issue:

During installation of an SSL Certificate on a Tomcat/jBoss system you may get the following error using keytool:

Error: “java.lang.Exception: Input not an X.509 certificate.”

Causes:

The cause of this error can happen for any of the following reasons.

  • Your version of Tomcat keytool will not accept a pkcs7/.p7b format certificate.
  • The certificate that you are importing into your keystore contains extra spaces. When keytool reads this file it sees the extra characters in its coding and Keytool is unable to read the certificate file.
  • You are installing a CSR or some other file instead of a x.509.
  • You can only install your SSL Certificate into the same keystore that was used to generate the CSR created to enroll for the SSL Certificate.
    • Conversions without a private key or taking an SSL Certificate that was created by means outside of the normal CSR Keytool generation will cause chaos during installation, and Keytool will display any error.

Resolutions:

If you receive this error when you are installing an SSL Certificate from any CA Into your keystore troubleshoot the following..

  1. Make sure that your certificate files you are creating to install into your keystore are clean and flush with no extra spaces.
    Opening your certificate file in notepad Do note use notepad++ words, etc. advanced document editors can add characters to your certificate.

    1. All certificate files should look like the example to the right.
    2. The —-Begin Certificate—- and the —-End Certificate—– Header and footers should be on their own lines.
    3. Notice that there are no double spaces in between lines or in between the coding.
    4. If you see irregularities with your certificate compared to the example provided then edit it to make it look like such.
  2. An x.509 certificate will look like the example provided.
    If your header and footer say —Begin Certificate Request— and —-End Certificate Request—- then it means you have been installing your CSR the whole time, thus the error. Find your SSL Certificate that has been misplaced.
  3. An SSL Certificate created from a CSR outside a Keytool environment is going to lead to a bad time.
    Conversions never work quite well with keytool or Oracle keystore/wallet type environments. Standard practice for is Keystore generation using Keytool > CSR creation from that Keystore > Enrollment of the SSL Certificate from the CA > Install the SSL Certificate issued from the CA.Below are Instruction on the X.509 Tomcat installation.
    SSL Installation instructions for Tomcat using X509

These instructions are created out of troubleshooting experience in dealing with the many issues of Keytool. If you are unable to use these instructions for your server, or you are still having issues with Keytool/Tomcat Acmetek recommends that you contact either the vendor of your software or the organization that supports it.

Oracle Support:
For more information, please refer to Keytool Support

Форум КриптоПро
 » 
Средства криптографической защиты информации
 » 
КриптоПро JCP, JavaTLS
 » 
Ошибка Input not an X.509 certificate при попытке импорта корневого сертификата тестового КП сервера


Offline

AlexanderOT1

 


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

10 июля 2020 г. 9:27:53(UTC)

AlexanderOT1

Статус: Участник

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

Зарегистрирован: 05.06.2020(UTC)
Сообщений: 25

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

Есть тестовый сервер Криптопро
http://testgost2012.cryptopro.ru/certsrv/
http://testgost2012.cryp….ru/certsrv/certcarc.asp

Написано
Чтобы доверять сертификатам, выданным этим центром сертификации, установите эту цепочку сертификатов ЦС.

Пробую импортировать в jcp-2.0.40502, Java7, Linux в cacerts
JCP установлено в Java командой setup_console, ошибок не было при установке.

/opt/java64/1.7.0_72/jre/bin/keytool -importcert -file «./certnew.cer» -alias CryptoPro_CA -keystore «/opt/java64/1.7.0_72/jre/lib/security/cacerts» -storepass changeit

или так

/opt/java64/1.7.0_72/jre/bin/keytool -J-Dkeytool.compat=true -J-Duse.cert.stub=true -provider ru.CryptoPro.JCP.JCP -importcert -file «./certnew.cer» -alias CryptoPro_CA -keystore «/opt/java64/1.7.0_72/jre/lib/security/cacerts» -storepass changeit

В обоих случаях выдается ошибка
keytool error: java.lang.Exception: Input not an X.509 certificate

Пробовал оба варианта:
Загрузка сертификата ЦС
Загрузка цепочки сертификатов ЦС

Пробовал импортировать сертификат ЦС в Windows, экспортировать его в
DER Encoded Binary X.509 (.CER)

Во всех вариантах одна и та же ошибка на Linux


Вверх


Offline

AlexanderOT1

 


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

10 июля 2020 г. 9:42:55(UTC)

AlexanderOT1

Статус: Участник

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

Зарегистрирован: 05.06.2020(UTC)
Сообщений: 25

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

Команда
C:Javajdk1.7.0_79jrebinkeytool -importcert -file «certnew.cer» -alias CryptoPro_CA -keystore «C:Javajdk1.7.0_79jrelibsecuritycacerts» -storepass changeit

На Windows сработала без ошибок


Вверх


Offline

AlexanderOT1

 


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

10 июля 2020 г. 12:50:11(UTC)

AlexanderOT1

Статус: Участник

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

Зарегистрирован: 05.06.2020(UTC)
Сообщений: 25

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

Скопировал cacerts из Java (Windows) в Java (Linux).

При попытке получить информацию о сертификате из cacerts он его находит, но выдает ошибку.

/opt/java64/1.7.0_72/jre/bin/keytool -list -v -keystore «/opt/java64/1.7.0_72/jre/lib/security/cacerts» -alias CryptoPro_CA

keytool error: java.security.cert.CertificateException: Certificate contains invalid public key: Unrecognized public key.
java.security.cert.CertificateException: Certificate contains invalid public key: Unrecognized public key.
at com.rsa.cryptoj.o.pk.g(Unknown Source)
at com.rsa.cryptoj.o.pk.<init>(Unknown Source)
at com.rsa.cryptoj.o.pj.<init>(Unknown Source)
at com.rsa.cryptoj.o.pg.a(Unknown Source)
at com.rsa.cryptoj.o.ot.engineGenerateCertificate(Unknown Source)
at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:339)
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:747)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
at java.security.KeyStore.load(KeyStore.java:1214)
at sun.security.tools.KeyTool.doCommands(KeyTool.java:789)
at sun.security.tools.KeyTool.run(KeyTool.java:340)
at sun.security.tools.KeyTool.main(KeyTool.java:333)


Вверх


Offline

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

 


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

10 июля 2020 г. 15:57:25(UTC)

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

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

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

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

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

Здравствуйте.

1. Команда:

Код:


/opt/java64/1.7.0_72/jre/bin/keytool -J-Dkeytool.compat=true -J-Duse.cert.stub=true -provider ru.CryptoPro.JCP.JCP -importcert -file "./certnew.cer" -alias CryptoPro_CA -keystore "/opt/java64/1.7.0_72/jre/lib/security/cacerts" -storepass changeit

некорректная, т.к. вы указали провайдер JCP, а работаете с cacerts, который имеет формат JKS, совершенно незнакомый JCP. Команды для работы с ключами и сертификатами лучше смотреть в руководствах разработчика и администратора в папке Doc дистрибутива, и будут они только с форматами, реализованными в JCP.

Команда:

Код:


C:Javajdk1.7.0_79jrebinkeytool -importcert -file "certnew.cer" -alias CryptoPro_CA -keystore "C:Javajdk1.7.0_79jrelibsecuritycacerts" -storepass changeit

корректная, т.к. java все равно, какой сертификат устанавливается, и провайдер используется по умолчанию (для JKS).

2.

Цитата:

При попытке получить информацию о сертификате из cacerts он его находит, но выдает ошибку.

/opt/java64/1.7.0_72/jre/bin/keytool -list -v -keystore «/opt/java64/1.7.0_72/jre/lib/security/cacerts» -alias CryptoPro_CA

keytool error: java.security.cert.CertificateException: Certificate contains invalid public key: Unrecognized public key.
java.security.cert.CertificateException: Certificate contains invalid public key: Unrecognized public key.
at com.rsa.cryptoj.o.pk.g(Unknown Source)
at com.rsa.cryptoj.o.pk.<init>(Unknown Source)
at com.rsa.cryptoj.o.pj.<init>(Unknown Source)
at com.rsa.cryptoj.o.pg.a(Unknown Source)
at com.rsa.cryptoj.o.ot.engineGenerateCertificate(Unknown Source)
at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:339)

В работу вмешивается какой-то провайдер com.rsa.cryptoj.

Отредактировано пользователем 10 июля 2020 г. 15:58:02(UTC)
 | Причина: Не указана

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


Вверх


Offline

AlexanderOT1

 


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

13 июля 2020 г. 23:01:30(UTC)

AlexanderOT1

Статус: Участник

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

Зарегистрирован: 05.06.2020(UTC)
Сообщений: 25

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

Спасибо, действительно, в jrelibsecurityjava.security есть регистрация нестандартного провайдера.
Может быть есть общие рекомендации, как разрешить этот конфликт, без отключения провайдера?
Судя по всему, провайдер нужен для другого компонента системы.


Вверх


Offline

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

 


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

14 июля 2020 г. 10:14:06(UTC)

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

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

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

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

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

Попробуйте указывать провайдер в keytool. Но надо учесть, что это не всегда помогает, так как, например, в случае декодирования открытого ключа сертификата поиск подходящего провайдера происходит по признаку, может ли этот провайдер декодировать ключ (поддерживает ли OID алгоритма ключа), и тогда важно положение провайдера в списке java.security (первый подходящий из списка будет декодировать). Обычно работу с ключами на иностранных алгоритмах обеспечивает встроенный провайдер типа Sun. Возможно, в списке java.security провайдер com.rsa.cryptoj (судя по названию пакета, он работает с иностранными алгоритмами) находится в начале списка и потому перехватывает обращения keytool к сертификату. Попробуйте переместить com.rsa.cryptoj в конец списка в java.security, сохраняя правильную нумерацию.

Отредактировано пользователем 14 июля 2020 г. 10:16:00(UTC)
 | Причина: Не указана

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


Вверх

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

Guest

Форум КриптоПро
 » 
Средства криптографической защиты информации
 » 
КриптоПро JCP, JavaTLS
 » 
Ошибка Input not an X.509 certificate при попытке импорта корневого сертификата тестового КП сервера

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

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

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

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

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

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

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

Понравилась статья? Поделить с друзьями:
  • Keytool error java lang exception failed to establish chain from reply
  • Keytool error java io ioexception keystore was tampered with or password was incorrect
  • Keytool error java io ioexception invalid keystore format
  • Keytool error java io ioexception incorrect ava format
  • Keytool error java io ioexception derinputstream getlength lengthtag 109 too big