Keytool error java io ioexception derinputstream getlength lengthtag 109 too big

Platform Notice: Server, Data Center, and Cloud By Request - This article was written for the Atlassian server and data center platforms but may also be useful for Atlassian Cloud customers. If completing instructions in this article would help you, please contact Atlassian Support and mention it.

Platform Notice: Server, Data Center, and Cloud By Request This article was written for the Atlassian server and data center platforms but may also be useful for Atlassian Cloud customers. If completing instructions in this article would help you, please contact Atlassian Support and mention it.

Problem

Issue occurs when trying to collect mail from a exchange mailbox.

This can be root cause of outgoing connection failures to Application Links too.

The below error appears in the logs:

 Caused by: java.security.KeyStoreException: problem accessing trust storejava.io.IOException: DerInputStream.getLength(): lengthTag=109, too big.
 at sun.security.ssl.TrustManagerFactoryImpl.engineInit(Unknown Source)
 at javax.net.ssl.TrustManagerFactory.init(Unknown Source)
 at org.apache.http.nio.conn.ssl.SSLLayeringStrategy.createSSLContext(SSLLayeringStrategy.java:85)
 at org.apache.http.nio.conn.ssl.SSLLayeringStrategy.createDefaultSSLContext(SSLLayeringStrategy.java:103)
 ... 41 more

Cause

  • The keystore configured for SSL couldn’t be read by keytool neither as JKS nor PKCS#12 keystore. So, this can affect Tomcat. 
  • Often how this error occurs is when certs are copied from Windows to Unix ie you have raised a CSR and you have received via email a signed certificate or a set of multiple signed certs from your certificate Authority. A CA could be Verisign or other main stream vendor or even the security team within your organization. 
  • There are extra characters found at the end of the certificate file which the “certificate parser” is attempting to interpret as the start or end of a certificate section. The most common way to encounter this error is to have one, or more, blank lines at the end of the certificate file.  A line termination sequence is permitted (but not required) at the end of the final “—–END”  line (Sometimes you may have more than one encoded cert in a file), but there can be no more than one termination sequence of characters. Reference to webspheretools.com.

Diagnose

PKCS#7/P7B Format

The PKCS#7 or P7B format is usually stored in Base64 ASCII format and has a file extention of .p7b or .p7c. P7B certificates contain «——BEGIN PKCS7——» and «——END PKCS7——» statements. A P7B file only contains certificates and chain certificates, not the private key. Several platforms support P7B files including Microsoft Windows and Java Tomcat.

PKCS#12/PFX Format

The PKCS#12 or PFX format is a binary format for storing the server certificate, any intermediate certificates, and the private key in one encryptable file. PFX files usually have extensions such as .pfx and .p12. PFX files are typically used on Windows machines to import and export certificates and private keys.

For more details you can refer to https://www.sslshopper.com/ssl-converter.html (External Site)

Resolution

  • Re-setup the Certificates
  • Remove the PKCS12 setting for trust store set in the service parameters, but have a back of your .PFX files!
  • Delete everything after the final “—–END” line.  Check the lines using a good editor that shows you the characters being used, don’t trust your eyes.
  • Having back up of the keystore always helps to restore it when disaster happens.

(warning) Unfortunately configuring/supporting SSL is not covered under since customers use a variety of products and configurations. A great way to get support for unsupported queries is to ask questions on , our active user-community Q&A site.Atlassian Support OfferingsAtlassian Answers

Когда я пытаюсь использовать java APNS для отправки push-уведомления в iOS, я получил это сообщение об ошибке:

com.notnoop.exceptions.InvalidSSLConfig: java.io.IOException: DerInputStream.getLength(): lengthTag = 109, слишком большой.

Я уже пытаюсь преобразовать сертификат в Personal Information Exchange (.p12), также получая ту же ошибку. Кто-нибудь знает проблему и как ее решить?

Вот мой код java:

ApnsService service =
    APNS.newService()
   .withCert("src/net/notification/ck.jks", "******")
   .withSandboxDestination()
   .build();

String payload = APNS.newPayload().alertBody(record.getSendMsg()).build();
String token = record.getToken();
service.push(token, payload);

Спасибо.

17 апр. 2014, в 08:57

Поделиться

Источник

4 ответа

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

Я вижу, что вы уже пытались преобразовать в .p12. Если вы сделали это правильно, возможно, есть другой формат по умолчанию. Я рекомендую узнать, как указать JKS.

user3251514
14 май 2014, в 19:48

Поделиться

У меня была такая же проблема, но мое решение поможет вам, только если вы используете maven.

Фильтрация ресурсов Maven (позволяющая включать переменные в файлы ресурсов) может испортить ваши двоичные файлы — и сертификаты особенно чувствительны к модификации.

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

<build>
    [...]
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <excludes>
                <exclude>**/*.p12</exclude>
            </excludes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
            <includes>
                <include>**/*.p12</include>
            </includes>
        </resource>
    </resources>
    [...]
</build>

Подробнее о фильтрации ресурсов maven:
http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

Zsolt Safrany
28 июль 2014, в 12:32

Поделиться

Если вы используете maven, это, вероятно, происходит из-за фильтрации Maven во всей папке ресурсов. Я пробовал решение Zsolt Safrany выше и не работал. Однако, прочитав документацию, которую он поделил, я нашел это:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-resources-plugin</artifactId>
  <version>3.0.1</version>
  <configuration>
    <nonFilteredFileExtensions>
      <nonFilteredFileExtension>p12</nonFilteredFileExtension>
    </nonFilteredFileExtensions>
  </configuration>
</plugin>

Это исключает возможность отфильтровывания двоичных расширений (или любого расширения, которое вы хотите).

alevilla86
30 июнь 2016, в 23:03

Поделиться

В моем случае я обнаружил, что что-то случайно изменило системное свойство javax.net.ssl.trustStore. Свойство отладки SSL -Djavax.net.debug=ssl:trustmanager мне очень помогло в расследовании.

bedla.czech
29 апр. 2019, в 14:13

Поделиться

Ещё вопросы

  • 0Удалить строку из таблицы
  • 0Power bi в Mysql на локальном хосте
  • 0Запуск приложения в фоновом режиме и перехват входящих и исходящих сообщений
  • 1XML десериализация в класс, добавить в список
  • 1Оправдывает ли необходимость упрощения кода использование неправильных абстракций?
  • 0Mysql — умножить два столбца и вычесть разницу
  • 1Сбой pytest: не удается найти запрошенный URL
  • 1Должен ли TypeConverter, предназначенный для преобразования в и из MyClass, быть в состоянии преобразовать MyClass
  • 0разрешить изменение URI в коде воспламенителя
  • 0Разница между пустыми и не пустыми функциями в C ++
  • 1Регулярное выражение для запрета запятых
  • 1Сбой соответствия групп Regex в Java
  • 0Мой контроллер мешает моей UI-маршрутизации
  • 1Использование EF Code First для ключевых таблиц / баз данных по идентификатору пользователя
  • 0Как перенаправить после самостоятельной публикации форму с атрибутами фильтра?
  • 1C # MVC2 Jqgrid — как правильно делать пейджинг на стороне сервера?
  • 1Значения не устанавливаются на слайсе с помощью .xs () и .get_level_values ()
  • 1Разрезать ряды панд между двумя массивами
  • 1Свойства муравья со специальными символами
  • 0Ошибка синтаксиса: отсутствует; до постановки СОЛР
  • 1Проверять на подчеркивание завернутые любые допустимые символы имени файла Windows, кроме подчеркивания и расширения csv
  • 0Галерея Fancybox, содержащая как встроенный контент, так и видео
  • 0LNK2019: неразрешенный внешний символ в функции
  • 0Задержка анимации ползунка и изменение эффекта на исчезновение?
  • 0Решить рекомендацию JSHint «Не использовать« с »»
  • 1Не могу получать трансляции в WinRT
  • 1Удалить все строки, которые являются дубликатами по отношению к некоторым строкам
  • 1Как я могу предотвратить смещение мяча с края экрана? простой пример KeyListenerDemo
  • 1Перезаписать файл Python при его использовании?
  • 0Войти через AngularJS
  • 0Альтернативный способ шаблона структуры со статической функцией-членом в CUDA?
  • 0Функция jquery для отображения текста по одному символу за раз
  • 1интеграция webpack и kafka-узла
  • 1Как получить результаты xml2js из анализатора в ES6?
  • 0В полях формы есть место
  • 0Spring Boot — Hibernate не сохраняет дату правильно
  • 0Как объединить массив по значению запятой?
  • 0Структура данных с TTL
  • 1Данные модели содержат специальные символы (например, «и»), которые должны отображаться в форме HTML
  • 0Синтаксическая ошибка MySQL 1064 с объединением запросов в MS Access
  • 0Как обновить комбинированный ящик кэндо в angularjs?
  • 0Как я могу получить и управлять потоковым ресурсом БД? PHP-DB2
  • 0Отображение массива ошибок структуры / класса C ++
  • 1Преобразование двойного 1.557760E12 в int
  • 1C # Обновление метки с изображением
  • 0Оператор << Перегрузка не работает правильно для комплексных чисел
  • 1Как избежать возобновления работы приложения на экране блокировки
  • 1Динамическая загрузка Java-класса против реализации LUA
  • 0Zend PDF загружал ttf с поддержкой языков, но по-прежнему не отображал символы, такие как русский или польский
  • 0Как создать таблицы для следующей модели данных?

Сообщество Overcoder

As a lot of users, I got tired of the SSL certificate error page every time I visit the controller’s page.

Unfortunately, Ubiquiti doesn’t provide an “easy” upload functionality through the web interface.

But they do provide some documentation, which seems easy and quick enough. Or so I thought.

Ubiquiti documentation

You can find the relevant documentation on the Ubiquiti online documentation page.

To import an SSL certificate, you simply need to use the java ace.jar located under the /usr/lib/unifi directory.

java -jar lib/ace.jar import_cert <signed_cert> [<other_intermediate_root_certs>...]

But this does not work for me. After running the above command, I got an error that the certificate could not be imported into the keystore.

Using the keytool

During my search for a solution, I came across a Git repository of Steve Jenkins. This repository includes a shell script for installing SSL certificates on the Unifi controller.

Being cautious using scripts from the internet, I searched for the commands that actually import the certificate.

I noticed the script uses the keytool utility to handle the SSL certificate import.

Before messing around with it, I first tried out and see what the keytool actually does.
In short, keytool is a key and certificate management utility. It allows users to administer their own public/private key pairs and associate certificates for self-authentication.
It also allows users to cache the public keys (in the form of certificates) of their communicating peers.

First, lets check and see what is stored inside the keystore.

You can do this by using the following command:

sudo keytool -list -keystore /var/lib/unifi/keystore

The keytool asks you to enter a password. The default keystore password is aircontrolenterprise .

Once you enter the password, you see a list of all the certificates currently present in the keystore.

Digging deeper into the script, you’ll see that you first need tot delete the cerficiate with the “unifi” alias before you import the new one. You can delete it using the following command:

sudo keytool -delete -alias unifi -keystore /var/lib/unifi/keystore 

After that you can run the keytool utility again to confirm that the certificate is no longer present.

Import your SSL certificate

The next step is to import the new SSL certificate. You can do this by running the following commands:

openssl pkcs12 -export -in <certificate.crt> -inkey <certificate_key.key>  -out <tempfile> -passout pass:aircontrolenterprise -name unifi
keytool -importkeystore -srckeystore <tempfile> -srcstoretype pkcs12 -srcstorepass aircontrolenterprise -destkeystore /var/lib/unifi/keystore -deststorepass aircontrolenterprise -deststoretype pkcs12 -alias unifi -trustcacerts

However, this did not do the tick for me. When importing the SSL certificate, I got the following error:

Keytool error: java.io.IOException: DerInputStream.getLength(): lengthTag=109, too big.

If you also get a similar error, you can try running the commands as follow:

openssl pkcs12 -export -nodes -out <tempfile> -inkey <certificate_key.key> -in <certificate.crt> -certfile <bundle.ca-bundle> -passout pass:aircontrolenterprise -name unifi
keytool -importkeystore -srckeystore <tempfile> -srcstorepass aircontrolenterprise -destkeystore /var/lib/unifi/keystore -deststorepass aircontrolenterprise -alias unifi -trustcacerts

This creates a new keystore in JKS format. Unifi does not have a problem with it, but when you list the certificates, you’ll see a warning like this:

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore /var/lib/unifi/keystore -destkeystore /var/lib/unifi/keystore -deststoretype pkcs12".

In addition, if you want to convert the keystore to the PKCS12 format, you can back it up and run the displayed command:

keytool -importkeystore -srckeystore /var/lib/unifi/keystore -destkeystore /var/lib/unifi/keystore -deststoretype pkcs12

The only thing left to do is to restart the Unifi controller and you are good to go!

systemctl restart unifi

I’m the founder of Netronix, a software company that specializes in Ruby / Ruby on Rails development.
I have been developing and deploying a wide variety of online business and content applications. Hands-on experience in Ruby & PHP, although my focus lies mostly on the cutting edge of Ruby / Rails programming.
View all posts by Michaël Rigart

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Keyless system malfunction ошибка на мазда
  • Keyguard остановлено как исправить на андроид
  • Keyguard остановлено как исправить на alcatel one touch
  • Keyframe obs как изменить
  • Keyerror python как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии