Статус: Новичок
Группы: Участники
Зарегистрирован: 28.08.2020(UTC) Сообщений: 1
Сказал(а) «Спасибо»: 1 раз
|
Здравствуйте! Очень прошу помощи! Нужно создать программу для формирования электронной подписи в формате CAdES_BES по алгоритму ГОСТ Р 34.10-2012. Однако, возникла непонятная проблема с ключами и сертификатами. Работаем в Linux. Точнее, в Docker-контейнерах на базе Linux. В файле приложенном forum.zip  forum.zip (11kb) загружен 4 раз(а). содержится всё, кроме дистрибутивов. Даже файлы сертификатов можно найти. После собственно установки CryptoPro CSP и Java CSP, запускается командная строка. Обмен файлами между контейнером и хозяйской машиной осуществляется через директорию storage/ (/mnt/storage/ в контейнере). Сначала скачал следующие сертификаты КриптоПро: http://testca2012.cryptopro.ru/cert/rootca.cer и http://testca2012.cryptopro.ru/cert/subca.cer , поместив их в дуректорию storage. В командной строке выполняю команду: Код:/opt/cprocsp/bin/amd64/cryptcp -createrqst -cont '\\.\HDIMAGE\forum' -sg -dn 'e=fo@rum.ru,cn=forum,c=rus' -pin 123456 /mnt/storage/forum.csr
...нажимаю на кнопки... Получаю файл CSR, запроса на создание сертификата. При помощи страницы http://www.cryptopro.ru/certsrv/certrqxt.asp получаю файлы forum.cer и forum.p7b, кладу их в storage/. Возвращаюсь в командную строку и выполняю команды: Код:/opt/cprocsp/bin/amd64/certmgr -inst -store uroot -file /mnt/storage/rootca.cer
/opt/cprocsp/bin/amd64/certmgr -inst -file /mnt/storage/subca.cer
keytool -keystore $JAVA_HOME/jre/lib/security/cacerts -importcert -alias forum -storepass changeit -noprompt -file /mnt/storage/rootca.cer
/opt/cprocsp/bin/amd64/certmgr -inst -all -file /mnt/storage/forum.p7b -at_signature
/opt/cprocsp/bin/amd64/cryptcp -instcert -cont '\\.\HDIMAGE\forum' -pin 123456 /mnt/storage/forum.cer
./compile.sh
./execute.sh
В итоге программа Sign.java (см. ниже) выдаёт ошибку: Код:Aug 28, 2020 12:09:33 PM ru.CryptoPro.JCP.tools.Starter check
INFO: Loading JCP 2.0.40424
Aug 28, 2020 12:09:33 PM ru.CryptoPro.JCP.tools.Starter check
INFO: JCP loaded.
Loaded keystore size: 1
The first alias: forum
Loaded certificate chain of size: 1
Aug 28, 2020 12:09:34 PM ru.CryptoPro.CAdES.tools.CAdESUtility initJCPAlgorithms
INFO: Replacement of the BouncyCastle GOST algorithms.
Exception in thread "main" java.lang.RuntimeException: Error building certification path for C=rus, CN=forum, EMAILADDRESS=fo@rum.ru: ru.CryptoPro.reprov.certpath.JCPCertPathBuilderException: unable to find valid certification path to requested target; error codes: [33] 'PKIX failure: invalid parameters of certificate',
at Sign.main(Sign.java:75)
Caused by: Error building certification path for C=rus, CN=forum, EMAILADDRESS=fo@rum.ru: ru.CryptoPro.reprov.certpath.JCPCertPathBuilderException: unable to find valid certification path to requested target; error codes: [33] 'PKIX failure: invalid parameters of certificate',
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.CryptoPro.CAdES.cl_1.addSigner(Unknown Source)
at ru.CryptoPro.CAdES.cl_1.addSigner(Unknown Source)
at Sign.main(Sign.java:60)
Caused by: Error building certification path for C=rus, CN=forum, EMAILADDRESS=fo@rum.ru: ru.CryptoPro.reprov.certpath.JCPCertPathBuilderException: unable to find valid certification path to requested target; error codes: [33] 'PKIX failure: invalid parameters of certificate',
at ru.CryptoPro.AdES.certificate.CertificateChainBuilderImpl.build(Unknown Source)
at ru.CryptoPro.AdES.certificate.CertificateChainBuilderImpl.build(Unknown Source)
... 6 more
Обращает на себя внимание странно короткая длина загруженной цепочки сертификатов. Всего один сертификат в цепочке, хотя, как видно выше, добавлена было вся цепочка из forum.p7b. Что я делаю не так? Какой-такой путь ещё надо куда-то и как-то добавить? *** ДОПОЛНЕНИЕ Из командной строки подписываю файл: Код:/opt/cprocsp/bin/amd64/cryptcp -sign -detached -fext .p7s /mnt/storage/Sign.java -dn CN=forum
Всё проходит "мирно": Код:CryptCP 5.0 (c) "Crypto-Pro", 2002-2020.
Command prompt Utility for file signature and encryption.
The following certificate will be used:
RDN:rus, forum, fo@rum.ru
Valid from 28.08.2020 11:56:52 to 28.11.2020 12:06:52
Certificate chain is not checked for this certificate:
RDN:rus, forum, fo@rum.ru
Valid from 28.08.2020 11:56:52 to 28.11.2020 12:06:52
The certificate or certificate chain is based on an untrusted root.
Do you want to use this certificate ([Y]es, [N]o, [C]ancel)?y
Certificate chains are checked.
Folder '/mnt/storage/':
/mnt/storage/Sign.java... Signing the data... 0%Crypto-Pro GOST R 34.10-2012 KC1 CSP requests password
Type password:
Signed message is created.
[ErrorCode: 0x00000000]
И проверка: Код:$ /opt/cprocsp/bin/amd64/cryptcp -verify -detached -fext .p7s /mnt/storage/Sign.java -dn CN=forum
CryptCP 5.0 (c) "Crypto-Pro", 2002-2020.
Command prompt Utility for file signature and encryption.
The following certificate will be used:
RDN:rus, forum, fo@rum.ru
Valid from 28.08.2020 11:56:52 to 28.11.2020 12:06:52
Certificate chain is not checked for this certificate:
RDN:rus, forum, fo@rum.ru
Valid from 28.08.2020 11:56:52 to 28.11.2020 12:06:52
The certificate or certificate chain is based on an untrusted root.
Do you want to use this certificate ([Y]es, [N]o, [C]ancel)?y
Certificate chains are checked.
Folder '/mnt/storage/':
/mnt/storage/Sign.java... Signature verifying...
Signer: rus, forum, fo@rum.ru
The certificate or certificate chain is based on an untrusted root.
Do you want to use this certificate ([Y]es, [N]o, [C]ancel)?y
Signature's verified.
[ErrorCode: 0x00000000]
Очень прошу помощи! *** Sign.java (построена на основе примеров): Код:import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.Base64;
import ru.CryptoPro.JCP.JCP;
import ru.CryptoPro.JCPRequest.GostCertificateRequest;
import ru.CryptoPro.CAdES.CAdESSignature;
import ru.CryptoPro.CAdES.CAdESType;
public class Sign {
static {
// Включаем возможность онлайновой проверки.
System.setProperty("com.sun.security.enableCRLDP", "true");
System.setProperty("com.ibm.security.enableCRLDP", "true");
}
public static void main(String[] argv) {
try {
// Load key store
KeyStore keyStore = KeyStore.getInstance(JCP.HD_STORE_NAME, JCP.PROVIDER_NAME);
keyStore.load(null, null);
System.out.println("Loaded keystore size: " + Integer.toString(keyStore.size()));
System.out.println("The first alias: " + keyStore.aliases().nextElement());
// Load certificate chain
Certificate[] chain = keyStore.getCertificateChain("forum");
System.out.println("Loaded certificate chain of size: " + Integer.toString(chain.length));
// The parameter's value set to true leads to generation of detached signature
CAdESSignature cadesSignature = new CAdESSignature(true);
cadesSignature.setCertificateStore(null);
cadesSignature.setCRLStore(null);
// Создаем подписанта CAdES-BES.
/*
cadesSignature.addSigner(JCP.PROVIDER_NAME,
JCP.GOST_DIGEST_2012_256_OID,
JCP.GOST_PARAMS_SIG_2012_256_KEY_OID,
(PrivateKey) keyStore.getKey("pecom-cr", "123456".toCharArray()),
Arrays.asList(chain),
CAdESType.CAdES_BES,
null,
false,
null,
null,
null);
*/
cadesSignature.addSigner(JCP.PROVIDER_NAME,
(PrivateKey) keyStore.getKey("forum", "123456".toCharArray()),
Arrays.asList(chain),
CAdESType.CAdES_BES,
null,
false);
ByteArrayOutputStream outSignatureStream = new ByteArrayOutputStream();
cadesSignature.open(outSignatureStream);
cadesSignatureUpdate(cadesSignature, new ByteArrayInputStream("Hello, world!".getBytes("UTF-8"))); // хеш
cadesSignature.close();
outSignatureStream.close();
System.out.println(Base64.getEncoder().encodeToString(outSignatureStream.toByteArray()));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static void cadesSignatureUpdate(CAdESSignature cAdESSignature,
InputStream dataStream) throws Exception {
final int buffer_size = 1024*1024;
byte[] buffer = new byte[buffer_size];
int read;
while ( (read = dataStream.read(buffer, 0, buffer_size)) > 0 ) {
cAdESSignature.update(buffer, 0, read);
} // while
}
}
Отредактировано пользователем 28 августа 2020 г. 17:25:30(UTC)
| Причина: Поменял команду keytool для добавления сертификата в cacerts, но на ошибку это не влияет
|