Stream does not represent a pkcs12 keystore egov вылазиет ошибка

В статье освещены основные проблемы при работе с сертификатами (ключами) ЭЦП НУЦ РК: -невозможно зайти в кабинет налогоплательщика, в egov.kz и др. сервисы еПравительства РК. …

В статье освещены основные проблемы при работе с сертификатами (ключами) ЭЦП НУЦ РК:

-невозможно зайти в кабинет налогоплательщика, в egov.kz и др. сервисы еПравительства РК.

-невозможно подписать, отправить документ, заявку и т.п.

В основе правильной работы большинства сервисов электронного правительства РК лежит установка утилиты NCA Layer, которая также содержит корневые сертификаты удостоверяющего центра. Поэтому, даже если какой-либо портал (например ЭСФ или кабинет налогоплательщика) не использует в работе данную утилиту, мы все же рекомендуем установить (обновить) ее.

ШАГ 1. Проверьте утилиту NCA Layer.

Если утилита никогда не устанавливалась то следует скачать ее и установить с сайта удостоверяющего центра по ссылке http://pki.gov.kz/index.php/ru/ncalayer

Необходимо проверить обновление утилиты, а также запущена ли она.

Значок этой уттилиты отображается в области уведомлений системы (возле значка переключения языков).

Значок выглядит так:  NCA Layer в трее

Если область уведомлений свернута то так:

NCA Layer в трее
Если значок есть, нажимаем на него правой кнопкой мыши и выбираем «Выход»
Теперь значок отсутствует. Далее запускаем утилиту NCA Layer  NCA Layer значок  с рабочего стола.
Если программа попросит обновится, то:
В окне с предложением обновления нажимаем «Загрузить». Даем в браузере разрешение на скачивание файла. Пока файл загружается, снова выходим из утилиты NCA Layer в области уведомлений, нажав на значок правой кнопкой мыши и выбрав «выход».
Запускаем скачанный файл. Программа сначала попросит удалить старую версию — соглашаемся. Затем, нажав «далее» несколько раз, устанавливаем новую версию утилиты.
Внимание! Во время установки антивирус может запросить разрешение на выполнение установки программы. Соглашаемся. В конце установки, встроенный файрвол Windows, возможно, так же попросит разрешения на использование программой сети интернет.

Так же проверьте установлены или обновлены ли модули утилиты. Для этого в области уведомлений нужно нажать правой кнопкой мыши на значок NCA Layer и выбрать «управление модулями».

Управление модулями NcaLayer

Проверьте, какие модули Вам нужны для работы и какие модули нужно установить. Например, модуль для работы на сайте Государственных закупок РК не устанавливается по умолчанию. Выберите этот модуль в списке и нажмите «Установить»

В ДОПОЛНЕНИЕ ВАЖНО!

Если Вы используете Кабинет Налогоплательщика, то также в NCA Layer необходимо установить Модуль knpplugin.

Более подробно о настройка кабинета налогоплательщика Вы можете прочесть в нашей статье https://pokompu.kz/кабинет-налогоплательщика/

Если Вы используете сайт Электронные счет-фактуры, то Вам необходимо установить модуль ЭСФ в NCA Layer

О дополнительных настройках и регистрации на портале ЭСФ читайте в нашей статье https://pokompu.kz/регистрация-на-портале-esf-gov-kz-электронны/

ШАГ 2. Проверяем настройки сертификатов и браузера
Выберите вариант браузера, с которым Вы работаете.

Вариант 1. Google Chrome

Если Вы используете Google Chrome, то дополнительные настройки не требуются.

[свернуть]

Вариант 2. Mozilla Firefox

Откройте браузер Mozilla Firefox 

Зайдите на официальный сайт >>> НУЦ РК <<<, чтобы установить корневые сертификаты.

Прокрутите вниз страницы и скачайте корневые сертификаты.

Корневые сертификаты НУЦ

Скопируйте и вставьте в адрес браузера firefox строку about:preferences#advanced или нажмите настройки Настройки firefox — дополнительные — сертификаты.

Далее щелкните «просмотр сертификатов» и выберите вкладку «Центры Сертификации»:

Центр сертификатов Firefox

Жмем «импортировать» и выбираем по порядку все 4 корневых сертификата, которые Вы скачали.

Закрываем браузер Firefox , открываем заново и пробуем воспользоваться сервисом электронного правительства.

[свернуть]

Вы можете также посмотреть короткое видео, как быстро проверить все настройки ЭЦП в компьютере (данное видео устарело, но в целом верно отражает настройки).

Не удалось решить проблему? Обращайтесь к нам через
форму обратной связи.

Или задавайте вопросы в комментариях ниже.

EJBCA, JEE PKI Certificate Authority

  • Summary

  • Files

  • Reviews

  • Support

  • Mailing Lists

  • News

  • Discussion

  • External Link ▾

    • Donate
    • Browse Git

Menu

CryptoToken activation failed: stream does not represent a PKCS12 key store


Created:

2015-07-16

Updated:

2015-07-24

  • Jie

    Hi everyone,

    I installed ejbca_ce_6_3_1_1 and jboss-as-6.0.0.Final, when I log in the admin page, it shows that Crypto Token State is off-line.
    I try to activate crypto token ManagementCA, the error comes out:
    CryptoToken activation failed: stream does not represent a PKCS12 key store

    Does anyone know what’s wrong with it?
    thank you.

  • Jie

    here is the server log:

    2015-07-16 18:18:19,176 [STDOUT] (pool-62-thread-1) Reloading CA certificate cache.

    2015-07-16 18:18:21,222 [STDOUT] (pool-15-thread-1) Error activating Crypto Token: with id -105709191. stream does not represent a PKCS12 key store

    2015-07-16 18:18:21,223 [STDOUT] (pool-15-thread-1) java.io.IOException: stream does not represent a PKCS12 key store

     

    Last edit: Jie 2015-07-16

  • Tomas Gustavsson

    jboss-as-6.0.0 is not an application server I recommend. You should use JBoss 7.1.1.GA instead, or JBoss EAP 6.

    Regards,
    Tomas

    • Jie

      Thanks Tomas, it works fine after I use jboss-as-7.1.1.Final instead of jboss-as-6.0.0.Final.

      However, when I use ws cli, another exception appears:
      java.net.SocketException: Software caused connection abort: recv failed

      Do you have any idea about this exception?

      The code is as below:

      CryptoProviderTools.installBCProvider();
      String urlstr = "https://localhost:8443/ejbca/ejbcaws/ejbcaws?wsdl";
      
      System.setProperty("javax.net.ssl.trustStore", "D:/Program_Files/ejbca_ce_6_3_1_1/p12/truststore.jks");
      System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
      
      System.setProperty("javax.net.ssl.keyStore", "D:/Program_Files/ejbca_ce_6_3_1_1/p12/superadmin.p12");
      System.setProperty("javax.net.ssl.keyStorePassword", "ejbca");
      
      System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");  
      Provider tlsProvider = new TLSProvider();  
      Security.addProvider(tlsProvider);  
      Security.setProperty("ssl.TrustManagerFactosry.algorithm", "AcceptAll");
      Security.setProperty("ssl.KeyManagerFactory.algorithm", "NewSunX509");
      
      QName qname = new QName("http://ws.protocol.core.ejbca.org/", "EjbcaWSService");
      EjbcaWSService service=null;
      try {
      service = new EjbcaWSService(new URL(urlstr), qname);
      } catch (MalformedURLException e) {
      e.printStackTrace();
      }
      EjbcaWS ejbcaraws = service.getEjbcaWSPort();
      System.out.println("Version: " + ejbcaraws.getEjbcaVersion());
      

      And the stack trace is in the attachment.

      Many thanks for your help.

  • Tomas Gustavsson

    Try using the EJBCA ClientToolbox to test WS connectivity. This to ensure your keystores work correctly,then you can conclude if the issue is in your code or not.

    • Jie

      Thanks for your reply.

      I type the following command in command line:
      ejbcaClientToolBox.bat ejbcawsracli finduser USERNAME EQUALS «superadmin»

      The user superadmin is found successfully.

      Does that mean there is something wrong with my code?
      I compare my code with class EJBCAWSRABaseCommand but find no errors. Do you have any suggestions regarding my code as shown before?

      Thank you.

    • Jie

      It works fine now!

      My code has no problem but my eclipse JBoss runtime is set to JBoss 6.0.
      All things go well after I change JBoss runtime to 7.1.
      Hope this would be helpful for others who meet the same problem.

      And thank Tomas again for kindly help.

       

      Last edit: Jie 2015-07-24


Log in to post a comment.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

marksherman opened this issue

Jan 14, 2016

· 12 comments

Assignees

@jisqyv

Comments

@marksherman

The client secret, needed to use a fusion tables service account, is now downloadable as a JSON file. There is no longer an option to download a .p12 file, which is what the FusionTablesControl component requires.

If the JSON file is attached, queries return the error «stream does not represent a PKCS12 key store»

That means App Inventor can’t be set up to use a new service account.

Here is the new JSON format (whitespace and client_id redaction by me)

{
  "installed":
  {
    "client_id":"000000000000000000000",
    "project_id":"grounded-style-118918",
    "auth_uri":"https://accounts.google.com/o/oauth2/auth",
    "token_uri":"https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs"
    }
  }

@halatmit @jsheldonmit @jisqyv @afmckinney

@halatmit

@jisqyv

@jisqyv

@marksherman I just created a service account and a p12 file was still an option…

That said, the p12 option is called «legacy» and the JSON path is preferred. So I will look into using a JSON key. NOTE: We will have to support both for a period of time, otherwise we will break existing projects that have and use p12 keys.

@halatmit

@marksherman

@jisqyv

@marksherman Did you go to the page to create a service credential? When I did, it gave me two radio buttons to choose from:

createcrentials

@jisqyv

@marksherman Btw. I believe I can do the change and still be backward compatible, but it will be ugly. The hard part is I likely will have to upgrade the version of the oauth2 library we are using AND all of its dependencies which may break other parts of App Inventor which will require fixing.

@marksherman

Wow, that’s hidden. If you click on the service account itself, you get this:
screen shot 2016-01-15 at 6 10 38 pm
With no indication that there’s another way to get it.

The secret is to not click on the service account, or click any of the TWO downloadJSON buttons on that page, but to go back up to «New Credentials» and select «service account key».

So no need for an immediate change, I’ll highlight that path in the instructions.

And still, I doubt most fourth grade teachers will be able to get it on the first, unaided try.

@halatmit

While you’re editi the Docs, should we simply tell people to use Service
Authorization and not worry about the other Authorization — or at least
describe things so that Service is the nornal way and describe the other a
an option (after we get it to work)?

== Hal Abelson
hal@mit.edu
Prof. of Comp. Sci. and Eng.
MIT Dept. of Elec. Eng. and Comp. Sci.

On Fri, Jan 15, 2016 at 6:14 PM, Mark Sherman notifications@github.com
wrote:

Wow, that’s hidden. If you click on the service account itself, you get
this:
[image: screen shot 2016-01-15 at 6 10 38 pm]
https://cloud.githubusercontent.com/assets/2035149/12367828/814f976e-bbb3-11e5-98d7-4e708a4f29e9.png
With no indication that there’s another way to get it.

The secret is to not click on the service account, or click any of the TWO
downloadJSON buttons on that page, but to go back up to «New Credentials»
and select «service account key».

So no need for an immediate change, I’ll highlight that path in the
instructions.

And still, I doubt most fourth grade teachers will be able to get it on
the first, unaided try.


Reply to this email directly or view it on GitHub
#675 (comment)
.

@marksherman

That’s actually my plan- not even mention the half-good solution

On Fri, Jan 15, 2016, 7:51 PM hal notifications@github.com wrote:

While you’re editi the Docs, should we simply tell people to use Service
Authorization and not worry about the other Authorization — or at least
describe things so that Service is the nornal way and describe the other a
an option (after we get it to work)?

== Hal Abelson
hal@mit.edu
Prof. of Comp. Sci. and Eng.
MIT Dept. of Elec. Eng. and Comp. Sci.

On Fri, Jan 15, 2016 at 6:14 PM, Mark Sherman notifications@github.com
wrote:

Wow, that’s hidden. If you click on the service account itself, you get
this:
[image: screen shot 2016-01-15 at 6 10 38 pm]
<
https://cloud.githubusercontent.com/assets/2035149/12367828/814f976e-bbb3-11e5-98d7-4e708a4f29e9.png

With no indication that there’s another way to get it.

The secret is to not click on the service account, or click any of the
TWO
downloadJSON buttons on that page, but to go back up to «New Credentials»
and select «service account key».

So no need for an immediate change, I’ll highlight that path in the
instructions.

And still, I doubt most fourth grade teachers will be able to get it on
the first, unaided try.


Reply to this email directly or view it on GitHub
<
#675 (comment)

.


Reply to this email directly or view it on GitHub
https://urldefense.proofpoint.com/v2/url?u=https-3A__github.com_mit-2Dcml_appinventor-2Dsources_issues_675-23issuecomment-2D172138425&d=BQMFaQ&c=lqHimbpwJeF7VTDNof4ddnO1LTp7jTaMHJ2UAxZwrfY&r=bJEpcfB0VesGOEw6RgFQuGv3sSGrcpElZuIXV_waLqM&m=c62XON7Q_D1vcmBqeevMVhv1rHgndVYQBIzy7Q2sLeA&s=RFiOgbJKXum38BkPy8NBhpgBp9IQE_1sg6bX_Vmvucw&e=
.

@halatmit

+1

== Hal Abelson
hal@mit.edu
Prof. of Comp. Sci. and Eng.
MIT Dept. of Elec. Eng. and Comp. Sci.

On Fri, Jan 15, 2016 at 7:59 PM, Mark Sherman notifications@github.com
wrote:

That’s actually my plan- not even mention the half-good solution

On Fri, Jan 15, 2016, 7:51 PM hal notifications@github.com wrote:

While you’re editi the Docs, should we simply tell people to use Service
Authorization and not worry about the other Authorization — or at least
describe things so that Service is the nornal way and describe the other
a
an option (after we get it to work)?

== Hal Abelson
hal@mit.edu
Prof. of Comp. Sci. and Eng.
MIT Dept. of Elec. Eng. and Comp. Sci.

On Fri, Jan 15, 2016 at 6:14 PM, Mark Sherman notifications@github.com
wrote:

Wow, that’s hidden. If you click on the service account itself, you get
this:
[image: screen shot 2016-01-15 at 6 10 38 pm]
<

https://cloud.githubusercontent.com/assets/2035149/12367828/814f976e-bbb3-11e5-98d7-4e708a4f29e9.png

With no indication that there’s another way to get it.

The secret is to not click on the service account, or click any of the
TWO
downloadJSON buttons on that page, but to go back up to «New
Credentials»
and select «service account key».

So no need for an immediate change, I’ll highlight that path in the
instructions.

And still, I doubt most fourth grade teachers will be able to get it on
the first, unaided try.


Reply to this email directly or view it on GitHub
<

#675 (comment)

.


Reply to this email directly or view it on GitHub
<
https://urldefense.proofpoint.com/v2/url?u=https-3A__github.com_mit-2Dcml_appinventor-2Dsources_issues_675-23issuecomment-2D172138425&d=BQMFaQ&c=lqHimbpwJeF7VTDNof4ddnO1LTp7jTaMHJ2UAxZwrfY&r=bJEpcfB0VesGOEw6RgFQuGv3sSGrcpElZuIXV_waLqM&m=c62XON7Q_D1vcmBqeevMVhv1rHgndVYQBIzy7Q2sLeA&s=RFiOgbJKXum38BkPy8NBhpgBp9IQE_1sg6bX_Vmvucw&e=

.


Reply to this email directly or view it on GitHub
#675 (comment)
.

@marksherman

The P12 is still available. Instructions have been updated to reflect how to get it.

Я разрабатываю проект Android.

У меня есть строка сертификата PEM:

-----BEGIN CERTIFICATE-----
MIIEczCCA1ugAwIBAgIBADANBgkqhkiG9w0BAQQFAD..AkGA1UEBhMCR0Ix
EzARBgNVBAgTClNvbWUtU3RhdGUxFDASBgNVBAoTC0..0EgTHRkMTcwNQYD
VQQLEy5DbGFzcyAxIFB1YmxpYyBQcmltYXJ5IENlcn..XRpb24gQXV0aG9y
...MANY LINES...
It8una2gY4l2O//on88r5IWJlm1L0oA8e4fR2yrBHX..adsGeFKkyNrwGi/
7vQMfXdGsRrXNGRGnX+vWDZ3/zWI0joDtCkNnqEpVn..HoX
-----END CERTIFICATE-----

(присвоенная строка сертификата переменной с именем CERT_STR)

Я декодирую выше строку PEM в массив байтов:

byte[] pemBytes = Base64.decode(
                CERT_STR.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")
                        .replaceAll("n", "")
                        .getBytes("UTF-8"),
                Base64.DEFAULT
        );

Я пытаюсь программно установить сертификат PEM на свой Android-телефон, выполнив следующий код:

Intent intent = KeyChain.createInstallIntent();
// because my PEM only contains a certificate, no private key, so I use EXTRA_CERTIFICATE
intent.putExtra(KeyChain.EXTRA_CERTIFICATE, pemBytes);// above PEM bytes
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

Когда я запускаю свой код (на устройстве Android 7), приложение установщика системных сертификатов Android всплывает окно, когда я нажимаю кнопку «ОК» этого окна, я получаю следующий журнал:

 java.io.IOException: stream does not represent a PKCS12 key store
  at com.android.org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.engineLoad(PKCS12KeyStoreSpi.java:793)
  at java.security.KeyStore.load(KeyStore.java:1247)
  at com.android.certinstaller.CredentialHelper.loadPkcs12Internal(CredentialHelper.java:396)
  at com.android.certinstaller.CredentialHelper.extractPkcs12Internal(CredentialHelper.java:364)
  at com.android.certinstaller.CredentialHelper.extractPkcs12(CredentialHelper.java:354)
  at com.android.certinstaller.CertInstaller$1.doInBackground(CertInstaller.java:328)
  at com.android.certinstaller.CertInstaller$1.doInBackground(CertInstaller.java:327)

Мои вопросы:

  • Я использовал EXTRA_CERTIFICATE и установил его в intent, я НЕ использую EXTRA_PKCS12, но из журнала система Android думает, что я устанавливаю хранилище ключей PKCS # 12. Почему?

  • Каков правильный способ программной установки сертификата PEM в Android?

Я разрабатываю проект Android.

У меня есть строка сертификата PEM:

-----BEGIN CERTIFICATE-----
MIIEczCCA1ugAwIBAgIBADANBgkqhkiG9w0BAQQFAD..AkGA1UEBhMCR0Ix
EzARBgNVBAgTClNvbWUtU3RhdGUxFDASBgNVBAoTC0..0EgTHRkMTcwNQYD
VQQLEy5DbGFzcyAxIFB1YmxpYyBQcmltYXJ5IENlcn..XRpb24gQXV0aG9y
...MANY LINES...
It8una2gY4l2O//on88r5IWJlm1L0oA8e4fR2yrBHX..adsGeFKkyNrwGi/
7vQMfXdGsRrXNGRGnX+vWDZ3/zWI0joDtCkNnqEpVn..HoX
-----END CERTIFICATE-----

(назначенная выше строка сертификата переменной с именем CERT_STR)

Я декодирую приведенную выше строку PEM в массив байтов:

byte[] pemBytes = Base64.decode(
                CERT_STR.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")
                        .replaceAll("n", "")
                        .getBytes("UTF-8"),
                Base64.DEFAULT
        );

Я пытаюсь программно установить сертификат PEM на свой телефон Android, используя следующий код:

Intent intent = KeyChain.createInstallIntent();
// because my PEM only contains a certificate, no private key, so I use EXTRA_CERTIFICATE
intent.putExtra(KeyChain.EXTRA_CERTIFICATE, pemBytes);// above PEM bytes
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

При запуске моего кода (на устройстве Android 7) приложение для установки системного сертификата Android открывает окно, когда я нажимаю кнопку «ОК» в этом окне, я получаю следующий журнал:

 java.io.IOException: stream does not represent a PKCS12 key store
  at com.android.org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.engineLoad(PKCS12KeyStoreSpi.java:793)
  at java.security.KeyStore.load(KeyStore.java:1247)
  at com.android.certinstaller.CredentialHelper.loadPkcs12Internal(CredentialHelper.java:396)
  at com.android.certinstaller.CredentialHelper.extractPkcs12Internal(CredentialHelper.java:364)
  at com.android.certinstaller.CredentialHelper.extractPkcs12(CredentialHelper.java:354)
  at com.android.certinstaller.CertInstaller$1.doInBackground(CertInstaller.java:328)
  at com.android.certinstaller.CertInstaller$1.doInBackground(CertInstaller.java:327)

Мои вопросы:

  1. Я использовал EXTRA_CERTIFICATE и установил для него intent, я НЕ использую EXTRA_PKCS12, но из журнала , Система Android думает, что я устанавливаю хранилище ключей PKCS#12. Почему?

  2. Как правильно программно установить сертификат PEM в Android?

1 ответ

Ваш код должен работать, как сказал @Sergey Nikitin. Этот отмеченный звездочкой пример в Github использует аналогичный код

Я просмотрел исходный код Android 7.1 CredentialHelper и CertInstaller для отслеживания журнала исключений. Уникальный доступный путь для выполнения загрузчика pkcs12 в

 com.android.certinstaller.CredentialHelper.extractPkcs12(CredentialHelper.java:354)

Это метод onScreenlockOk

private void onScreenlockOk() {
    if (mCredentials.hasPkcs12KeyStore()) {
        if (mCredentials.hasPassword()) {
            showDialog(PKCS12_PASSWORD_DIALOG);
        } else {
            new Pkcs12ExtractAction("").run(this);
        }

Который защищен CredentialHelper.hasPkcs12KeyStore()

boolean hasPkcs12KeyStore() {
    return mBundle.containsKey(KeyChain.EXTRA_PKCS12);
}

Я не нашел значений по умолчанию или альтернативных путей, поэтому делаю вывод, что KeyChain.EXTRA_PKCS12 каким-то образом используется. Это странное поведение, может быть, у вас проблема с очисткой и восстановлением?

Я предлагаю отлаживать код, включая класс Android CertInstaller, чтобы обеспечить значения Extras и гарантировать, что исполняемый код является ожидаемым.


0

pedrofb
13 Ноя 2016 в 23:44

Понравилась статья? Поделить с друзьями:
  • Stream connection error
  • Stoloto как изменить номер телефона
  • Stmt php error
  • Stm32cubeide error launching installer
  • Stm32 uart overrun error