Статус: Новичок
Группы: Участники
Зарегистрирован: 13.02.2024(UTC) Сообщений: 1
|
Добрый день. Работаю над сервисом для шифрования данных с использованием КриптоПРО. Застрял на этапе авторизации. В моём случае используется сценарий авторизации с аутентификацией по сертификату. Сертификат в формате pfx. Делаю согласно документации: https://dss.cryptopro.ru...ationcode-flow-cert.htmlЧто было сделано c сертификатом и настройками КриптоПРО:
- Установил КриптоПро CSP (5.0.12997) и КриптоПро Java CSP (5.0.42119-A)
- Импортировал контейнер с закрытым ключом как HDImageStore используя CryptoPro Tools. При импорте сертификаты были автоматически распределены по хранилищам:
- Доверенные корневые центры сертификации
- Промежуточные центры сертификации
- Личное
- Используя Java CSP Control Pane создал хранилище (truststore.store) и добавил в него все 3 сертификата из цепочки:
2024-02-16 14_45_45-CryptoPro JCP settings.png (44kb) загружен 10 раз(а).
Проект реализован на Java с использованием Spring Boot 3.2.2 и Maven. Инициализация SSLContext происходит следующим образом:
Код:
private void initCryptoPro(JavaCSPProperties jcspProps) {
log.info("Initializing CryptoPro Java CSP");
Security.addProvider(new JCP());
Security.addProvider(new CryptoProvider());
Security.addProvider(new RevCheck());
Security.addProvider(new Provider());
Security.setProperty("ssl.TrustManagerFactory.algorithm", Provider.KEYMANGER_ALG);
Security.setProperty("ssl.KeyManagerFactory.algorithm", Provider.KEYMANGER_ALG);
Security.setProperty("ssl.SocketFactory.provider", "ru.CryptoPro.ssl.SSLSocketFactoryImpl");
Security.setProperty("ssl.ServerSocketFactory.provider", "ru.CryptoPro.ssl.SSLServerSocketFactoryImpl");
System.setProperty("com.sun.security.enableCRLDP", "true");
System.setProperty("com.ibm.security.enableCRLDP", "true");
System.setProperty("javax.net.ssl.supportGVO", "true");
System.setProperty("javax.net.ssl.trustStoreType", "CertStore");
System.setProperty("javax.net.ssl.trustStore", jcspProps.getTrustKeyStore().getPath());
System.setProperty("javax.net.ssl.trustStorePassword", jcspProps.getTrustKeyStore().getPassword());
log.info("CryptoPro Java CSP was initialized");
}
private SSLContext buildSSLContext(String trustStorePath,
String trustStorePassword,
String keyStorePassword) {
try {
log.info("Building SSL context");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(Provider.KEYMANGER_ALG);
tmf.init(loadTrustKeyStore(trustStorePath, trustStorePassword));
KeyManagerFactory kmf = KeyManagerFactory.getInstance(Provider.KEYMANGER_ALG);
kmf.init(loadKeyStore(), keyStorePassword.toCharArray());
SSLContext sslCtx = SSLContext.getInstance(Provider.ALGORITHM_12);
sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
log.info("SSL context was built");
return sslCtx;
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyManagementException e) {
log.error("Error building SSL context: {}", e.getMessage(), e);
throw new RuntimeException("Error building SSL context", e);
}
}
private KeyStore loadKeyStore() {
try {
log.info("Loading key store");
KeyStore keyStore = KeyStore.getInstance(JCP.HD_STORE_NAME);
keyStore.load(null);
return keyStore;
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
log.error("Error loading key store: {}", e.getMessage(), e);
throw new RuntimeException("Error loading key store", e);
}
}
private KeyStore loadTrustKeyStore(String path, String password) {
try {
log.info("Loading trust key store");
KeyStore trustKeyStore = KeyStore.getInstance(JCP.HD_STORE_NAME);
trustKeyStore.load(new FileInputStream(path), password.toCharArray());
return trustKeyStore;
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
log.error("Error loading trust key store: {}", e.getMessage(), e);
throw new RuntimeException("Error loading trust key store", e);
}
}
Для отправки запроса на получение кода авторизации использую HttpsURLConnection:
Код:
public void connect() {
SSLContext sslCtx = buildSSLContext(jcspProps.getTrustKeyStore().getPath(),
jcspProps.getTrustKeyStore().getPassword(),
jcspProps.getKeyStore().getPassword());
URL url = jcspProps.getAuthorization().buildRequestUrl();
String authCode = getAuthorizationCode(sslCtx.getSocketFactory(), url);
}
private String getAuthorizationCode(SSLSocketFactory socketFactory, URL url) {
log.info("Getting authorization code");
HttpsURLConnection connection = null;
try {
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(socketFactory);
connection.setRequestMethod("GET");
connection.connect();
String authCode;
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
authCode = extractAuthCode(connection);
log.info("Authorization code was obtained");
} else {
log.warn("Failed to get authorization code");
handleError(connection);
authCode = null;
}
return authCode;
} catch (IOException e) {
log.error("Error getting authorization code: {}", e.getMessage(), e);
throw new RuntimeException("Error getting authorization code", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Но в результате получаю ошибку: 403 - запрещено. Доступ запрещен. Предоставленные учетные данные не дают права на просмотр этого каталога или страницы.В логах есть следующие строки:
Код:
FINER: Downloading new CRL...
февр. 16, 2024 2:58:28 PM ru.CryptoPro.reprov.certpath.DistributionPointFetcher a
FINER: Exception verifying CRL:
java.lang.IllegalArgumentException: The key cannot be null
at ru.CryptoPro.reprov.certpath.DisabledAlgorithmConstraints.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.DisabledAlgorithmConstraints.permits(Unknown Source)
at ru.CryptoPro.reprov.certpath.AlgorithmChecker.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.AlgorithmChecker.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.DistributionPointFetcher.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.DistributionPointFetcher.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.DistributionPointFetcher.getCRLs(Unknown Source)
at ru.CryptoPro.reprov.certpath.CrlRevocationChecker.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.CrlRevocationChecker.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.CrlRevocationChecker.check(Unknown Source)
at java.base/sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:224)
at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:144)
at java.base/sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:83)
at java.base/java.security.cert.CertPathValidator.validate(CertPathValidator.java:309)
at ru.CryptoPro.reprov.CPCertPathValidator.engineValidate(Unknown Source)
at java.base/java.security.cert.CertPathValidator.validate(CertPathValidator.java:309)
at ru.CryptoPro.ssl.pc_4.cl_2.a(Unknown Source)
at ru.CryptoPro.ssl.pc_4.cl_2.a(Unknown Source)
at ru.CryptoPro.ssl.pc_4.cl_4.b(Unknown Source)
at ru.CryptoPro.ssl.cl_115.a(Unknown Source)
at ru.CryptoPro.ssl.cl_115.a(Unknown Source)
at ru.CryptoPro.ssl.cl_115.checkServerTrusted(Unknown Source)
at ru.CryptoPro.ssl.cl_18.a(Unknown Source)
at ru.CryptoPro.ssl.cl_18.a(Unknown Source)
at ru.CryptoPro.ssl.cl_60.t(Unknown Source)
at ru.CryptoPro.ssl.cl_60.a(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.a(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.o(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.b(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:578)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:187)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:142)
at com.bellintegrator.gpbsb.cryptoproadapter.client.CryptoProDssClient.getAuthorizationCode(CryptoProDssClient.java:60)
at com.bellintegrator.gpbsb.cryptoproadapter.client.CryptoProDssClient.connect(CryptoProDssClient.java:49)
at com.bellintegrator.gpbsb.cryptoproadapter.CryptoproAdapterApplication.main(CryptoproAdapterApplication.java:15)
Код:
FINER: Exception fetching CRL: http://sub-testca2012/cdp/c410ac0963611b223c66b0a9c1564377288f293e.crl (status: -1)
февр. 16, 2024 2:58:31 PM ru.CryptoPro.reprov.certpath.URICertStore engineGetCRLs
FINER: THROW
java.net.UnknownHostException: sub-testca2012
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:560)
at java.base/java.net.Socket.connect(Socket.java:666)
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:178)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:531)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:636)
at java.base/sun.net.www.http.HttpClient.<init>(HttpClient.java:279)
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:384)
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:406)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1308)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1241)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1127)
at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1056)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1661)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1585)
at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:529)
at ru.CryptoPro.reprov.certpath.URICertStore.engineGetCRLs(Unknown Source)
at java.base/java.security.cert.CertStore.getCRLs(CertStore.java:182)
at ru.CryptoPro.reprov.certpath.DistributionPointFetcher.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.DistributionPointFetcher.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.DistributionPointFetcher.getCRLs(Unknown Source)
at ru.CryptoPro.reprov.certpath.CrlRevocationChecker.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.CrlRevocationChecker.a(Unknown Source)
at ru.CryptoPro.reprov.certpath.CrlRevocationChecker.check(Unknown Source)
at java.base/sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:224)
at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:144)
at java.base/sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:83)
at java.base/java.security.cert.CertPathValidator.validate(CertPathValidator.java:309)
at ru.CryptoPro.reprov.CPCertPathValidator.engineValidate(Unknown Source)
at java.base/java.security.cert.CertPathValidator.validate(CertPathValidator.java:309)
at ru.CryptoPro.ssl.pc_4.cl_2.a(Unknown Source)
at ru.CryptoPro.ssl.pc_4.cl_2.a(Unknown Source)
at ru.CryptoPro.ssl.pc_4.cl_4.b(Unknown Source)
at ru.CryptoPro.ssl.cl_115.a(Unknown Source)
at ru.CryptoPro.ssl.cl_115.a(Unknown Source)
at ru.CryptoPro.ssl.cl_115.checkServerTrusted(Unknown Source)
at ru.CryptoPro.ssl.cl_18.a(Unknown Source)
at ru.CryptoPro.ssl.cl_18.a(Unknown Source)
at ru.CryptoPro.ssl.cl_60.t(Unknown Source)
at ru.CryptoPro.ssl.cl_60.a(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.a(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.o(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.b(Unknown Source)
at ru.CryptoPro.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:578)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:187)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:142)
at com.bellintegrator.gpbsb.cryptoproadapter.client.CryptoProDssClient.getAuthorizationCode(CryptoProDssClient.java:60)
at com.bellintegrator.gpbsb.cryptoproadapter.client.CryptoProDssClient.connect(CryptoProDssClient.java:49)
at com.bellintegrator.gpbsb.cryptoproadapter.CryptoproAdapterApplication.main(CryptoproAdapterApplication.java:15)
При попытке открыть в браузере ссылку на запрос кода авторизации со всеми необходимыми параметрами, запрашивается сертификат с паролем от хранилища закрытого ключа, затем открывается пустая страница. Может кто-то подскажет, в чём может быть проблема? Возможно я упустил какие-то шаги по добавлению и настройке сертификатов? Или же неправильно конфигурирую Java CSP или SSLContext? Полный лог с уровнем логирования ALL для JCPLogger: cryptopro_adapter.log (135kb) загружен 2 раз(а).Отредактировано пользователем 16 февраля 2024 г. 15:34:28(UTC)
| Причина: Добавил фрагменты кода
|