Показаны сообщения с ярлыком OpenSSL. Показать все сообщения
Показаны сообщения с ярлыком OpenSSL. Показать все сообщения

вторник, 22 ноября 2022 г.

Convert a X.509 Certificate from Metadata

 Source

There are times that you might need to provide or have access to a X.509 certificate to verify the validity of a signed key or some other piece of data. X.509 Certificates are a standard for public key certificates and are often used to validate signatures on tokens and assertions used during user authentication, for example, when authenticating using SAML (Security Assertion Markup Language).

Recently, I needed to provide an X.509 certificate, provided by an Identity Provider, Azure AD, to an authorization service provider, Auth0. Since the X.509 certificate is a public format, the identity provider makes the certificate available in a long string format from their Federation Metadata Document, which is an .xml file publicly available. The format for the X.509 certificate provided by Azure was encoded in a base64 format, which was not accepted as is by Auth0, I needed to do some conversion prior to uploading to Auth0.

The following are steps taken to obtain and transform the X.509 certificate into a usable format across parties, (not all steps might be necessary for your use case):

  1. Obtain the X.509 certificate from the Identity Provider

Azure presents the X.509 certificate in the Federation Metadata Document which is a publicly available .xml document. In the metadata, there might be more than one X.509 certificate defined, this is because the certificates have differing expiration dates. If one certificate has expired, an application could then try to use another X.509 defined in the metadata for their validation needs.

Example .xml certificate

1
2
3
4
5
6
7
8
9
10
11
<KeyDescriptor use="signing">
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<X509Data>
<X509Certificate>
MIIDBTCCAe2gAwIBAgIQWPB1ofOpA7FFlOBk5iPaNTANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIxMDIwNzE3MDAzOVoXDTI2MDIwNjE3MDAzOVowLTErMCkGA1UEAxMiYWNjb3VudHMu
....
bmMCnFWuNNahcaAKiJTxYlKDaDIiPN35yECYbDj0PBWJUxobrvj5I275jbikkp8QSLYnSU/v7dMDUbxSLfZ7zsTuaF2Qx+L62PsYTwLzIFX3M8EMSQ6h68TupFTi5n0M2yIXQgoRoNEDWNJZ/aZMY/gqT02GQGBWrh+/vJ
</X509Certificate>
</X509Data>
</KeyInfo>
</KeyDescriptor>

  1. Copy/Paste value of <X509Certificate>…</X509Certificate>

To get the certificate into format we can work with, copy/paste the value in between the <X509Certificate> .xml elements into a new .crt file.

A valid .crt certificate file contains a BEGIN and END certificate declaration. Your file should look something like this:

Example .crt file

1
2
3
4
5
-----BEGIN CERTIFICATE-----
MIIDBTCCAe2gAwIBAgIQWPB1ofOpA7FFlOBk5iPaNTANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIxMDIwNzE3MDAzOVoXDTI2MDIwNjE3MDAzOVowLTErMCkGA1UEAxMiYWNjb3VudHMu
....
bmMCnFWuNNahcaAKiJTxYlKDaDIiPN35yECYbDj0PBWJUxobrvj5I275jbikkp8QSLYnSU/v7dMDUbxSLfZ7zsTuaF2Qx+L62PsYTwLzIFX3M8EMSQ6h68TupFTi5n0M2yIXQgoRoNEDWNJZ/aZMY/gqT02GQGBWrh+/vJ
-----END CERTIFICATE-----

  1. Make .crt file valid

The current format of the .crt file is not actually a valid certificate format. We need to “fold” the long base64 string into one where each line of the certificate is 64 characters in length. This can be easily done with the fold command.

1
fold -w 64 example.crt > new-example.crt

This command will read our example.crt, perform the fold action to wrap each line after the 64th character, and then write the output to a new file with the new format.

  1. Convert .crt to .pem

Our example.crt might be acceptable, but I’ve found most relying parties need the X.509 certificate in a different format, often a .pem format. To convert the .crt to a .pem format we will use the openssl utility to convert between formats.

1
openssl x509 -in new-example.crt -out example.pem

The converted certificate can now be uploaded to the relying party.

While the steps are a bit manual, they can likely be improved and streamlined with scripting, etc. These certificates are often valid for many years or forever, so this should not be a process that needs to be performed often.

четверг, 28 мая 2015 г.

Проверка SSL и ключа

Чтобы проверить соответствие сертификата ключу (проверить ssl и ключ) в консоли вводим:
# openssl x509 -noout -modulus -in /путь/до/сертификата/cert.crt | openssl md5
# openssl rsa -noout -modulus -in
/путь/до/ключа/my_key.key | openssl md5

         # openssl rsa -check -noout -in myserver.key

If it doesn't say 'RSA key ok', it isn't OK!" 

Если совпадает хеш MD5 — значит сертификат соответсвует ключу.
Так же есть удобный онлайн сервис проверки ssl и ключа:
https://www.sslshopper.com/certificate-key-matcher.html

среда, 4 февраля 2015 г.

Экспорт закрытого ключа ЭЦП из rutoken.

Источник, благодарю автора.

1. Предположим у вас уже есть сертификат (электронная подпись) на USB носителе, называется эта штука «Рутокен». Если нет, приобретаем у любого аккредитованного удостоверяющего центра, список см. на сайте zapret-info.gov.ru

2. Нужно установить сертификат с электронного ключа Рутокен на локальную машину под управлением Windows. Подробно описано тут

3. Когда сертификат установлен, нужно экспортировать ключ в формате PKCS#12 из криптоконтейнера в Windows с помощью утилиты P12FromGostCSP , в итоге у нас получится файл p12.pfx . Закидываем его на сервер с FreeBSD, Windows нам больше не понадобится

4. Собираем из исходников openssl с поддержкой алгоритмов нашего ГОСТ. В openssl.cnf:

В самом начале, до начала всех секций:
openssl_conf = openssl_def
В конце новые секции:
[openssl_def]
engines=engine_section
[engine_section]
gost=gost_section
[gost_section]
engine_id=gost
default_algorithms=ALL
 5. Преобразуем файл p12.pfx из формата PKCS#12 в PEM вот такой командой:
 openssl pkcs12 -in p12.pfx -out p12.pem -nodes -clcerts