### Install Test Certificate with CryptCP
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-samples.md
Command to install a test certificate using the cryptcp utility. This is a prerequisite for running the PyCAdES examples that require a certificate with a private key.
```bash
export PATH="/opt/cprocsp/bin/amd64:/opt/cprocsp/bin/aarch64:$PATH" && \
cryptcp -createcert -dn "CN=test" -provtype 80 -cont '\\.\\HDIMAGE\\test' -ca https://cryptopro.ru/certsrv
```
--------------------------------
### Install CryptoPro CSP on Ubuntu
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-build.md
Install CryptoPro CSP and related packages (lsb-cprocsp-devel, cprocsp-pki-cades, cprocsp-legacy) after unpacking the downloaded archive.
```bash
tar xvf linux-amd64_deb.tgz
cd linux-amd64_deb
sudo ./install.sh lsb-cprocsp-devel cprocsp-legacy cprocsp-pki-cades
```
--------------------------------
### Install pycades using pip
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-install.md
Use this command to install the pycades extension. Ensure you have a virtual environment activated.
```bash
uv venv && \
source .venv/bin/activate && \
uv pip install -v .
```
--------------------------------
### Install Ubuntu Build Dependencies
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-build.md
Install necessary packages for building PyCades on Ubuntu 24.04, including cmake, build-essential, libboost-all-dev, and python3-dev.
```bash
sudo apt install cmake build-essential libboost-all-dev python3-dev
```
--------------------------------
### XML Signing Setup in PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Initializes PyCades for signing XML documents, including opening a certificate store and setting up the signer object. The XML content to be signed is also defined.
```python
import pycades
# Открытие хранилища и получение сертификата
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE,
pycades.CAPICOM_MY_STORE,
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
assert store.Certificates.Count != 0, "Сертификаты с закрытым ключом не найдены"
# Настройка подписанта
signer = pycades.Signer()
signer.Certificate = store.Certificates.Item(1)
# XML-документ для подписания
xml_content = '''
Тестовый документ
2024-01-15
Важные данные для подписания
Описание документа
'''
```
--------------------------------
### Create and Verify Signature with PyCAdES
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-samples.md
Example of creating and verifying a digital signature using PyCAdES. Ensure you have a certificate with a private key.
```python
from pycades import CadesSignature, SignedData, Certificate, Signer, Options
def sign_verify():
# Load certificate
cert = Certificate.from_pem("path/to/your/certificate.cer")
# Data to sign
data = b"This is the data to be signed."
# Create signature
signer = Signer(cert)
signed_data = SignedData(data)
signature = CadesSignature.sign(signed_data, signer, Options.CONTENT_SIGNATURE)
# Verify signature
is_valid = signature.verify()
print(f"Signature is valid: {is_valid}")
if __name__ == "__main__":
sign_verify()
```
--------------------------------
### Enumerate Certificate Containers with PyCAdES
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-samples.md
Example of how to list available certificate containers on the system using PyCAdES. This is often a prerequisite for selecting a certificate for signing or decryption.
```python
from pycades import Container
def enum_containers():
containers = Container.enum_containers()
print("Available certificate containers:")
for container in containers:
print(f"- {container.name} (Provider: {container.provider_name})")
if __name__ == "__main__":
enum_containers()
```
--------------------------------
### Create and Verify XML Signature with PyCAdES
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-samples.md
Example demonstrating how to create and verify a digital signature for XML documents using PyCAdES. This involves specific handling for XML structures.
```python
from pycades import CadesXMLSignature, Certificate, Signer
def sign_verify_xml():
# Load certificate
cert = Certificate.from_pem("path/to/your/certificate.cer")
# XML data to sign
xml_data = "data"
# Create XML signature
signer = Signer(cert)
xml_signature = CadesXMLSignature.sign(xml_data, signer)
# Verify XML signature
is_valid = xml_signature.verify()
print(f"XML signature is valid: {is_valid}")
if __name__ == "__main__":
sign_verify_xml()
```
--------------------------------
### Create and Verify CAdES Signature
Source: https://context7.com/cryptopro/pycades/llms.txt
Example of creating and verifying a CAdES-BES signature using PyCades. Ensure certificates with private keys are available in the store.
```python
import pycades
# Открытие хранилища и получение сертификата
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE,
pycades.CAPICOM_MY_STORE,
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
assert store.Certificates.Count != 0, "Сертификаты с закрытым ключом не найдены"
# Настройка подписанта
signer = pycades.Signer()
signer.Certificate = store.Certificates.Item(1)
signer.CheckCertificate = True # Проверять сертификат при подписании
# Для метки времени (CAdES-T и выше)
# signer.TSAAddress = "http://tsp.cryptopro.ru/tsp/tsp.srf"
# Создание подписи CAdES-BES
signed_data = pycades.SignedData()
signed_data.Content = "Данные для подписания"
# Подписание (CADESCOM_CADES_BES, CADESCOM_CADES_T, CADESCOM_CADES_X_LONG_TYPE_1)
signature = signed_data.SignCades(
signer,
pycades.CADESCOM_CADES_BES # Тип подписи CAdES-BES
)
print("=== Подпись создана ===")
print(signature[:100] + "...")
# Проверка подписи
verify_data = pycades.SignedData()
verify_data.VerifyCades(
signature,
pycades.CADESCOM_CADES_BES
)
print("Подпись успешно проверена")
print(f"Подписанные данные: {verify_data.Content}")
# Получение информации о подписантах
print(f"Количество подписей: {verify_data.Signers.Count}")
for i in range(1, verify_data.Signers.Count + 1):
s = verify_data.Signers.Item(i)
print(f"Подписант {i}: {s.Certificate.SubjectName}")
print(f"Время подписания: {s.SigningTime}")
store.Close()
```
--------------------------------
### About - Get Version Information
Source: https://context7.com/cryptopro/pycades/llms.txt
The About object provides version information for the CAdES library and the cryptographic service provider (CSP).
```APIDOC
## About - Get Version Information
### Description
Retrieves version details for the Pycades library, CAdES components, and the CryptoPro CSP.
### Method
Instantiate the `pycades.About` object and access its properties.
### Parameters
None
### Request Example
```python
import pycades
about = pycades.About()
print(f"Library Version: {about.Version}")
print(f"Major Version: {about.MajorVersion}")
print(f"Minor Version: {about.MinorVersion}")
print(f"Build Version: {about.BuildVersion}")
plugin_version = about.PluginVersion
print(f"Plugin Version: {plugin_version.toString()}")
csp_version = about.CSPVersion("", 75)
print(f"CSP Version: {csp_version.MajorVersion}.{csp_version.MinorVersion}.{csp_version.BuildVersion}")
print(f"Pycades Module Version: {pycades.ModuleVersion()}")
```
### Response
Information about the versions of the library, plugin, and CSP.
```
--------------------------------
### Encrypt and Decrypt Data with PyCAdES
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-samples.md
Example showing how to encrypt and decrypt data using PyCAdES. This typically involves recipient certificates for encryption and the corresponding private key for decryption.
```python
from pycades import EncryptedData, Certificate, Decryptor
def encrypt_decrypt_data():
# Load recipient certificate for encryption
recipient_cert = Certificate.from_pem("path/to/recipient/certificate.cer")
# Data to encrypt
data = b"This is the sensitive data."
# Encrypt data
encrypted_data = EncryptedData.encrypt(data, [recipient_cert])
# Load your certificate and private key for decryption
my_cert = Certificate.from_pem("path/to/your/certificate.cer")
decryptor = Decryptor(my_cert)
# Decrypt data
decrypted_data = encrypted_data.decrypt(decryptor)
print(f"Decrypted data: {decrypted_data.decode()}")
if __name__ == "__main__":
encrypt_decrypt_data()
```
--------------------------------
### Work with Certificate Revocation Lists (CRL) using PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Provides examples for creating, importing, exporting, and adding Certificate Revocation Lists (CRLs) to a certificate store using PyCades. Note that some operations are commented out and require specific CRL data.
```python
import pycades
crl = pycades.CRL()
crl_base64 = """
MIIBkjCB/AIBATANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJSVTEPMA0GA1UE
...
"""
# crl.Import(crl_base64)
# print(f"Издатель: {crl.IssuerName}")
# print(f"Идентификатор ключа издателя: {crl.AuthKeyID}")
# print(f"Отпечаток: {crl.Thumbprint}")
# print(f"Дата выпуска: {crl.ThisUpdate}")
# print(f"Дата следующего обновления: {crl.NextUpdate}")
# exported_crl = crl.Export(pycades.CAPICOM_ENCODE_BASE64)
# print(f"CRL (Base64): {exported_crl}")
store = pycades.Store()
store.Open(
pycades.CADESCOM_LOCAL_MACHINE_STORE,
"CA",
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
# store.AddCRL(crl)
store.Close()
print("Работа с CRL завершена")
```
--------------------------------
### PyCades Module Constants Overview
Source: https://context7.com/cryptopro/pycades/llms.txt
Lists and provides examples of various constants available in the pycades module. These constants are used to configure signature types, hashing and encryption algorithms, store locations, and encoding methods.
```python
import pycades
# Типы подписи CAdES
CADES_TYPES = {
'BES': pycades.CADESCOM_CADES_BES, # Базовая подпись
'T': pycades.CADESCOM_CADES_T, # С меткой времени
'X_LONG_TYPE_1': pycades.CADESCOM_CADES_X_LONG_TYPE_1, # Расширенная
}
# Типы подписи XAdES
XADES_TYPES = {
'BES': pycades.CADESCOM_XADES_BES,
'T': pycades.CADESCOM_XADES_T,
'X_LONG_TYPE_1': pycades.CADESCOM_XADES_X_LONG_TYPE_1,
}
# Типы XML-подписи
XML_SIGNATURE_TYPES = {
'ENVELOPED': pycades.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED, # Встроенная
'ENVELOPING': pycades.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING, # Охватывающая
'TEMPLATE': pycades.CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE, # По шаблону
}
# Алгоритмы хэширования
HASH_ALGORITHMS = {
'GOST_3411': pycades.CADESCOM_HASH_ALGORITHM_CP_GOST_3411,
'GOST_3411_2012_256': pycades.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256,
'GOST_3411_2012_512': pycades.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512,
'SHA1': pycades.CADESCOM_HASH_ALGORITHM_SHA1,
'SHA256': pycades.CADESCOM_HASH_ALGORITHM_SHA_256,
'SHA384': pycades.CADESCOM_HASH_ALGORITHM_SHA_384,
'SHA512': pycades.CADESCOM_HASH_ALGORITHM_SHA_512,
}
# Алгоритмы шифрования
ENCRYPTION_ALGORITHMS = {
'GOST_28147_89': pycades.CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89,
'3DES': pycades.CADESCOM_ENCRYPTION_ALGORITHM_3DES,
'AES': pycades.CADESCOM_ENCRYPTION_ALGORITHM_AES,
}
# Типы хранилищ
STORE_LOCATIONS = {
'CURRENT_USER': pycades.CADESCOM_CURRENT_USER_STORE,
'LOCAL_MACHINE': pycades.CADESCOM_LOCAL_MACHINE_STORE,
'CONTAINER': pycades.CADESCOM_CONTAINER_STORE,
'MEMORY': pycades.CADESCOM_MEMORY_STORE,
}
# Имена стандартных хранилищ
STORE_NAMES = {
'MY': pycades.CAPICOM_MY_STORE, # Личные сертификаты
'CA': pycades.CAPICOM_CA_STORE, # Промежуточные УЦ
'ROOT': pycades.CAPICOM_ROOT_STORE, # Корневые сертификаты
}
# Критерии поиска сертификатов
FIND_TYPES = {
'SHA1_HASH': pycades.CAPICOM_CERTIFICATE_FIND_SHA1_HASH,
'SUBJECT_NAME': pycades.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME,
'ISSUER_NAME': pycades.CAPICOM_CERTIFICATE_FIND_ISSUER_NAME,
'TIME_VALID': pycades.CAPICOM_CERTIFICATE_FIND_TIME_VALID,
'TIME_EXPIRED': pycades.CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED,
}
# Кодировки
ENCODINGS = {
'BASE64': pycades.CADESCOM_ENCODE_BASE64,
'BINARY': pycades.CADESCOM_ENCODE_BINARY,
'ANY': pycades.CADESCOM_ENCODE_ANY,
}
# Пример использования констант
print("=== Основные константы pycades ===")
for name, value in CADES_TYPES.items():
print(f"CAdES {name}: {value}")
```
--------------------------------
### Get Pycades and CSP Version Information
Source: https://context7.com/cryptopro/pycades/llms.txt
Use the About object to retrieve version details for the Pycades library, its plugin, and the CryptoPro CSP. This is useful for diagnostics and compatibility checks.
```python
import pycades
# Создание объекта About
about = pycades.About()
# Получение информации о версии библиотеки
print(f"Версия: {about.Version}")
print(f"Major: {about.MajorVersion}")
print(f"Minor: {about.MinorVersion}")
print(f"Build: {about.BuildVersion}")
# Получение версии плагина
plugin_version = about.PluginVersion
print(f"Версия плагина: {plugin_version.toString()}")
# Получение версии криптопровайдера CSP (provType=75 по умолчанию)
csp_version = about.CSPVersion("", 75)
print(f"Версия CSP: {csp_version.MajorVersion}.{csp_version.MinorVersion}.{csp_version.BuildVersion}")
# Получение версии модуля pycades
print(f"Версия модуля pycades: {pycades.ModuleVersion()}")
```
--------------------------------
### Create and Verify Detached CAdES-BES Signature by Hash
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-samples.md
Example for creating and verifying a detached CAdES-BES signature based on the hash value of the data. This is useful when the original data cannot be directly processed.
```python
from pycades import CadesSignature, SignedData, Certificate, Signer, Options
import hashlib
def sign_verify_hash():
# Load certificate
cert = Certificate.from_pem("path/to/your/certificate.cer")
# Data to sign
data = b"This is the data to be signed."
data_hash = hashlib.sha256(data).digest()
# Create signature
signer = Signer(cert)
signed_data = SignedData(data_hash)
signature = CadesSignature.sign(signed_data, signer, Options.CONTENT_SIGNATURE, detached=True)
# Verify signature
# For verification, you would need the original data to recompute the hash
# or have the hash value provided separately.
# Here we assume the hash is available for verification.
is_valid = signature.verify(data_hash=data_hash)
print(f"Detached signature is valid: {is_valid}")
if __name__ == "__main__":
sign_verify_hash()
```
--------------------------------
### Access and Iterate Through Certificate Store
Source: https://context7.com/cryptopro/pycades/llms.txt
The Store object allows access to Windows/Linux certificate stores. Open a store, retrieve certificates, and iterate through them to get details like subject, issuer, serial number, validity dates, and thumbprint. Supports finding certificates by SHA1 hash or subject name.
```python
import pycades
# Открытие хранилища контейнеров с закрытыми ключами
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE, # Хранилище контейнеров
pycades.CAPICOM_MY_STORE, # Личные сертификаты "My"
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED # Максимальные права доступа
)
# Получение коллекции сертификатов
certs = store.Certificates
print(f"Найдено сертификатов: {certs.Count}")
# Перебор всех сертификатов (индекс начинается с 1)
for i in range(1, certs.Count + 1):
cert = certs.Item(i)
print(f"Субъект: {cert.SubjectName}")
print(f"Издатель: {cert.IssuerName}")
print(f"Серийный номер: {cert.SerialNumber}")
print(f"Действителен с: {cert.ValidFromDate}")
print(f"Действителен до: {cert.ValidToDate}")
print(f"Отпечаток: {cert.Thumbprint}")
print(f"Есть закрытый ключ: {cert.HasPrivateKey()}")
print("---")
# Поиск сертификата по отпечатку SHA1
thumbprint = "1234567890ABCDEF1234567890ABCDEF12345678"
found_certs = certs.Find(
pycades.CAPICOM_CERTIFICATE_FIND_SHA1_HASH,
thumbprint,
0 # validOnly: 0 - все, 1 - только валидные
)
# Поиск сертификатов по имени субъекта
found_by_name = certs.Find(
pycades.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME,
"CN=test",
0
)
# Закрытие хранилища
store.Close()
```
--------------------------------
### Run PyCades Sample in Docker
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-build.md
Execute the sign_verify.py sample script within the built pycades-build Docker container.
```bash
docker run pycades-build python3 samples/sign_verify.py
```
--------------------------------
### Sign and Verify XML with PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Demonstrates how to create a signed XML document using enveloped signature type and XAdES-BES, and subsequently verify the signature. Ensure the signer object is properly initialized before use.
```python
import pycades
# Assume xml_content and signer are defined elsewhere
# xml_content = "data"
# signer = pycades.Signer()
# Создание объекта для подписи XML
signed_xml = pycades.SignedXML()
signed_xml.Content = xml_content
# Тип подписи: enveloped + XAdES-BES
signed_xml.SignatureType = (
pycades.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED |
pycades.CADESCOM_XADES_BES
)
# Подписание документа
signature = signed_xml.Sign(signer)
print("=== Подписанный XML-документ ===")
print(signature[:200] + "...")
# Проверка подписи XML
verify_xml = pycades.SignedXML()
verify_xml.Content = "" # Очищаем перед проверкой
verify_xml.Verify(signature)
# После проверки Content содержит подписанный документ
verified_content = verify_xml.Content
print("XML-подпись успешно проверена")
print(f"Проверенный документ совпадает: {signature == verified_content}")
# Получение информации о подписях
print(f"Количество подписей: {verify_xml.Signers.Count}")
# store.Close() # Assuming store is opened elsewhere and needs closing
```
--------------------------------
### Build Docker Image for PyCades
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-build.md
Build the Docker image tagged as 'pycades-build' from the Dockerfile in the current directory.
```bash
docker build -t pycades-build .
```
--------------------------------
### Copy CSP Packages to Docker Build Context
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-build.md
Before building the Docker image, copy the CryptoPro CSP package directory into the same directory as the Dockerfile.
```bash
cp -r ~/csp/ .
```
--------------------------------
### Symmetric Encryption with GOST 28147-89
Source: https://context7.com/cryptopro/pycades/llms.txt
Demonstrates symmetric encryption and decryption using the SymmetricAlgorithm class with GOST 28147-89. Requires opening a certificate store to export/import keys. Ensure correct mode and padding are set.
```python
import pycades
# Открытие хранилища для получения сертификата
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE,
pycades.CAPICOM_MY_STORE,
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
cert = store.Certificates.Item(1)
# Создание объекта симметричного алгоритма
sym_alg = pycades.SymmetricAlgorithm()
# Генерация симметричного ключа
sym_alg.GenerateKey(pycades.CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89)
# Установка режима шифрования
sym_alg.SetMode(pycades.CRYPT_MODE_CBCSTRICT) # CBC режим
# Установка дополнения (padding)
sym_alg.SetPadding(pycades.PKCS5_PADDING)
# Получение вектора инициализации (IV)
iv = sym_alg.IV
print(f"Вектор инициализации: {iv}")
# Шифрование данных
plaintext = "Данные для симметричного шифрования"
ciphertext = sym_alg.Encrypt(plaintext, pycades.CADESCOM_ENCODE_BASE64)
print(f"Зашифрованные данные: {ciphertext[:50]}...")
# Расшифрование данных
decrypted = sym_alg.Decrypt(ciphertext, pycades.CADESCOM_ENCODE_BASE64)
print(f"Расшифрованные данные: {decrypted}")
# Экспорт ключа на сертификате получателя
exported_key = sym_alg.ExportKey(cert)
print(f"Экспортированный ключ: {exported_key[:50]}...")
# Импорт ключа (на стороне получателя)
sym_alg2 = pycades.SymmetricAlgorithm()
sym_alg2.ImportKey(exported_key, cert)
# Диверсификация ключа
# sym_alg.DiversData = "diversification_data"
# sym_alg.DiversifyKey()
store.Close()
```
--------------------------------
### Sign and Verify Hash in PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Demonstrates creating and verifying an detached signature using a pre-calculated hash value. This is efficient for large files. Ensure the correct hash algorithm is used.
```python
import pycades
# Открытие хранилища и получение сертификата
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE,
pycades.CAPICOM_MY_STORE,
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
assert store.Certificates.Count != 0, "Сертификаты с закрытым ключом не найдены"
# Настройка подписанта
signer = pycades.Signer()
signer.Certificate = store.Certificates.Item(1)
signer.CheckCertificate = True
# Вычисление хэша данных
hashed_data = pycades.HashedData()
hashed_data.Algorithm = pycades.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256 # ГОСТ 34.11-2012 256 бит
# Хэширование данных (можно вызывать несколько раз для больших данных)
hashed_data.Hash("первая часть данных")
hashed_data.Hash("вторая часть данных")
# Получение хэш-значения
print(f"Хэш-значение: {hashed_data.Value}")
# Подписание хэша
signed_data = pycades.SignedData()
signature = signed_data.SignHash(
hashed_data,
signer,
pycades.CADESCOM_CADES_BES
)
print("=== Отсоединённая подпись по хэшу создана ===")
print(signature[:100] + "...")
# Проверка подписи по хэшу
# Для проверки нужно заново вычислить хэш от тех же данных
verify_hash = pycades.HashedData()
verify_hash.Algorithm = pycades.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256
verify_hash.Hash("первая часть данных")
verify_hash.Hash("вторая часть данных")
verify_data = pycades.SignedData()
verify_data.VerifyHash(
verify_hash,
signature,
pycades.CADESCOM_CADES_BES
)
print("Подпись по хэшу успешно проверена")
store.Close()
```
--------------------------------
### Build PyCades Library
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-build.md
Compile the PyCades library using 'make'. If it fails, attempt 'make rebuild-library'.
```bash
make || make rebuild-library
```
--------------------------------
### Store - Certificate Store Operations
Source: https://context7.com/cryptopro/pycades/llms.txt
The Store object provides access to certificate stores (Windows/Linux), allowing you to open stores, retrieve certificate collections, and search for certificates.
```APIDOC
## Store - Certificate Store Operations
### Description
Manages access to certificate stores, enabling retrieval and searching of certificates.
### Method
Instantiate the `pycades.Store` object, use the `Open` method to access a store, and then interact with the `Certificates` collection.
### Parameters
#### Open Method Parameters
- **StoreType** (int) - Required - Type of the store (e.g., `pycades.CADESCOM_CONTAINER_STORE`).
- **Location** (int) - Required - Location of the store (e.g., `pycades.CAPICOM_MY_STORE`).
- **OpenMode** (int) - Required - Access mode (e.g., `pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED`).
### Request Example
```python
import pycades
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE,
pycades.CAPICOM_MY_STORE,
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
certs = store.Certificates
print(f"Number of certificates found: {certs.Count}")
for i in range(1, certs.Count + 1):
cert = certs.Item(i)
print(f"Subject: {cert.SubjectName}")
print(f"Issuer: {cert.IssuerName}")
print(f"Serial Number: {cert.SerialNumber}")
print(f"Valid From: {cert.ValidFromDate}")
print(f"Valid To: {cert.ValidToDate}")
print(f"Thumbprint: {cert.Thumbprint}")
print(f"Has Private Key: {cert.HasPrivateKey()}")
print("---")
# Find certificate by SHA1 thumbprint
thumbprint = "1234567890ABCDEF1234567890ABCDEF12345678"
found_certs = certs.Find(
pycades.CAPICOM_CERTIFICATE_FIND_SHA1_HASH,
thumbprint,
0
)
# Find certificates by subject name
found_by_name = certs.Find(
pycades.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME,
"CN=test",
0
)
store.Close()
```
### Response
- **Count** (int) - The number of certificates in the store.
- **Item(index)** (Certificate object) - Retrieves a certificate by its index.
- **Find(type, value, validOnly)** (Certificate object or collection) - Finds certificates based on specified criteria.
```
--------------------------------
### Enumerate Containers and Keys with PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Iterates through all available cryptographic containers and their associated keys, printing detailed information about each. Requires access to cryptographic hardware or software providers.
```python
containers = csp_info.EnumContainers()
print(f"Найдено контейнеров: {containers.Count}")
for i in range(containers.Count):
container = containers.ItemByIndex(i)
print(f"\n=== Контейнер #{i + 1} ===")
print(f"Уникальное имя: {container.UniqueName}")
print(f"Имя: {container.Name}")
print(f"Считыватель: {container.Reader}")
print(f"Носитель: {container.Media}")
print(f"FQCN: {container.FQCN}")
keys = container.Keys
print(f"Количество ключей: {keys.Count}")
for j in range(keys.Count):
key = keys.ItemByIndex(j)
print(f"\n Ключ #{j + 1}:")
print(f" Экспортируемый: {key.IsExportable}")
print(f" Срок действия: {key.ExpirationTime}")
if hasattr(key, 'PublicKey'):
pub_key = key.PublicKey
print(f" Алгоритм: {pub_key.Algorithm.Value}")
print(f" Длина ключа: {pub_key.Length} бит")
if hasattr(key, 'KP_FP'):
print(f" Отпечаток ключа: {key.KP_FP}")
if hasattr(key, 'KP_ALGID'):
print(f" ID алгоритма: {key.KP_ALGID}")
print(f" Есть сертификат: {key.HasCertificate}")
if key.HasCertificate:
cert = key.Certificate
pub_key = cert.PublicKey()
print(f" Субъект: {cert.SubjectName}")
print(f" Издатель: {cert.IssuerName}")
print(f" Серийный номер: {cert.SerialNumber}")
print(f" Действителен с: {cert.ValidFromDate} UTC")
print(f" Действителен до: {cert.ValidToDate} UTC")
print(f" Отпечаток: {cert.Thumbprint}")
print(f" Алгоритм ключа: {pub_key.Algorithm.FriendlyName}")
print(f" Длина ключа: {pub_key.Length} бит")
```
--------------------------------
### Add Signing Attributes to a Signature with PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Demonstrates how to create and attach custom attributes like signing time, document name, and description to an electronic signature using PyCades. Requires a valid certificate from a store.
```python
import pycades
from datetime import datetime
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE,
pycades.CAPICOM_MY_STORE,
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
cert = store.Certificates.Item(1)
attr_time = pycades.Attribute()
attr_time.Name = pycades.CADESCOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME
attr_time.Value = datetime.now().strftime("%Y%m%d%H%M%S.000000Z")
attr_doc_name = pycades.Attribute()
attr_doc_name.Name = pycades.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME
attr_doc_name.Value = "Договор №123"
attr_doc_desc = pycades.Attribute()
attr_doc_desc.Name = pycades.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION
attr_doc_desc.Value = "Договор поставки товаров"
signer = pycades.Signer()
signer.Certificate = cert
signer.CheckCertificate = True
signer.AuthenticatedAttributes.Add(attr_time)
signer.AuthenticatedAttributes.Add(attr_doc_name)
signer.AuthenticatedAttributes.Add(attr_doc_desc)
signed_data = pycades.SignedData()
signed_data.Content = "Содержимое документа"
signature = signed_data.SignCades(signer, pycades.CADESCOM_CADES_BES)
print("Подпись с атрибутами успешно создана")
print(f"Атрибут времени: {attr_time.Value}")
print(f"Имя документа: {attr_doc_name.Value}")
print(f"Описание: {attr_doc_desc.Value}")
store.Close()
```
--------------------------------
### Retrieve Certificate Details and Private Key Information
Source: https://context7.com/cryptopro/pycades/llms.txt
The Certificate object provides access to X.509 certificate details, including subject/issuer names, serial number, validity periods, and thumbprint. It can also retrieve extended information, check for a private key, and access public key details.
```python
import pycades
# Открытие хранилища и получение сертификата
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE,
pycades.CAPICOM_MY_STORE,
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
cert = store.Certificates.Item(1)
# Получение информации о сертификате
print(f"Субъект: {cert.SubjectName}")
print(f"Издатель: {cert.IssuerName}")
print(f"Серийный номер: {cert.SerialNumber}")
print(f"Версия сертификата: {cert.Version}")
print(f"Действителен с: {cert.ValidFromDate}")
print(f"Действителен до: {cert.ValidToDate}")
print(f"Отпечаток (SHA1): {cert.Thumbprint}")
# Получение расширенной информации
simple_name = cert.GetInfo(pycades.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME)
issuer_name = cert.GetInfo(pycades.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME)
email = cert.GetInfo(pycades.CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME)
print(f"Простое имя: {simple_name}")
print(f"Имя издателя: {issuer_name}")
print(f"Email: {email}")
# Проверка наличия закрытого ключа
if cert.HasPrivateKey():
cert.FindPrivateKey() # Поиск и привязка закрытого ключа
private_key = cert.PrivateKey
print(f"Имя контейнера: {private_key.ContainerName}")
print(f"Провайдер: {private_key.ProviderName}")
print(f"Тип провайдера: {private_key.ProviderType}")
# Получение информации об открытом ключе
public_key = cert.PublicKey()
print(f"Алгоритм ключа: {public_key.Algorithm.FriendlyName}")
print(f"OID алгоритма: {public_key.Algorithm.Value}")
print(f"Длина ключа: {public_key.Length} бит")
```
--------------------------------
### Enumerate Cryptographic Containers with CspInformation in PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Retrieves information about the cryptographic service provider (CSP) and enumerates cryptographic containers. This is useful for identifying available cryptographic resources.
```python
import pycades
# Получение информации о криптопровайдере
about = pycades.About()
csp_name = about.CSPName(80) # Тип провайдера 80 = ГОСТ 2012
# Инициализация информации о CSP
csp_info = pycades.CspInformation()
csp_info.InitializeFromName(csp_name)
# Further operations would involve EnumContainers() on csp_info
```
--------------------------------
### Certificate Operations in PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Demonstrates checking certificate validity, exporting to Base64, and importing from Base64 using PyCades.
```python
cert_status = cert.IsValid()
print(f"Сертификат валиден: {cert_status.Result}")
```
```python
cert_base64 = cert.Export(pycades.CAPICOM_ENCODE_BASE64)
print(f"Сертификат (Base64): {cert_base64[:50]}...")
```
```python
new_cert = pycades.Certificate()
new_cert.Import(cert_base64)
print(f"Импортированный сертификат: {new_cert.SubjectName}")
```
--------------------------------
### Clone PyCades Repository
Source: https://github.com/cryptopro/pycades/blob/main/doc/pycades-build.md
Clone the PyCades source code from the GitHub repository.
```bash
git clone https://github.com/CryptoPro/pycades.git
cd pycades
```
--------------------------------
### Certificate - Certificate Object Operations
Source: https://context7.com/cryptopro/pycades/llms.txt
The Certificate object represents an X.509 public key certificate, allowing you to retrieve certificate details, check validity, and access associated private keys.
```APIDOC
## Certificate - Certificate Object Operations
### Description
Provides detailed information about a digital certificate and allows interaction with its associated private key.
### Method
Obtain a `Certificate` object, typically from a `Store`'s `Certificates` collection, and then access its properties and methods.
### Parameters
None directly for the object, but methods like `GetInfo` take parameters.
### Request Example
```python
import pycades
# Assuming 'cert' is a Certificate object obtained from a Store
# Example: cert = store.Certificates.Item(1)
# Get basic certificate information
print(f"Subject: {cert.SubjectName}")
print(f"Issuer: {cert.IssuerName}")
print(f"Serial Number: {cert.SerialNumber}")
print(f"Version: {cert.Version}")
print(f"Valid From: {cert.ValidFromDate}")
print(f"Valid To: {cert.ValidToDate}")
print(f"Thumbprint (SHA1): {cert.Thumbprint}")
# Get extended information
simple_name = cert.GetInfo(pycades.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME)
issuer_name = cert.GetInfo(pycades.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME)
email = cert.GetInfo(pycades.CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME)
print(f"Simple Name: {simple_name}")
print(f"Issuer Name: {issuer_name}")
print(f"Email: {email}")
# Check for and access private key
if cert.HasPrivateKey():
cert.FindPrivateKey() # Find and associate the private key
private_key = cert.PrivateKey
print(f"Container Name: {private_key.ContainerName}")
print(f"Provider Name: {private_key.ProviderName}")
print(f"Provider Type: {private_key.ProviderType}")
# Get public key information
public_key = cert.PublicKey()
print(f"Key Algorithm: {public_key.Algorithm.FriendlyName}")
print(f"Algorithm OID: {public_key.Algorithm.Value}")
print(f"Key Length: {public_key.Length} bits")
```
### Response
- **SubjectName** (string) - The subject distinguished name of the certificate.
- **IssuerName** (string) - The issuer distinguished name of the certificate.
- **SerialNumber** (string) - The serial number of the certificate.
- **Version** (int) - The version of the certificate.
- **ValidFromDate** (datetime) - The date from which the certificate is valid.
- **ValidToDate** (datetime) - The date until which the certificate is valid.
- **Thumbprint** (string) - The SHA1 hash of the certificate.
- **HasPrivateKey()** (bool) - Returns true if a corresponding private key is available.
- **PrivateKey** (PrivateKey object) - Access to the associated private key object (after calling `FindPrivateKey`).
- **PublicKey()** (PublicKey object) - Returns an object containing information about the public key.
- **GetInfo(type)** (string) - Retrieves specific certificate information based on the provided type constant (e.g., `CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME`).
```
--------------------------------
### Encrypt and Decrypt Data with EnvelopedData in PyCades
Source: https://context7.com/cryptopro/pycades/llms.txt
Encrypts a message using the recipient's public key and decrypts it using their private key. Supports encryption for multiple recipients. Ensure certificates with private keys are available in the store.
```python
import pycades
# Открытие хранилища и получение сертификата получателя
store = pycades.Store()
store.Open(
pycades.CADESCOM_CONTAINER_STORE,
pycades.CAPICOM_MY_STORE,
pycades.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
)
assert store.Certificates.Count != 0, "Сертификаты с закрытым ключом не найдены"
# Получение сертификата получателя (с открытым ключом для шифрования)
recipient_cert = store.Certificates.Item(1)
# Шифрование данных
enveloped_data = pycades.EnvelopedData()
enveloped_data.Content = "Секретное сообщение для шифрования с русскими буквами"
# Добавление получателей (можно добавить несколько)
enveloped_data.Recipients.Add(recipient_cert)
# Шифрование (CADESCOM_ENCODE_BASE64 или CADESCOM_ENCODE_BINARY)
encrypted_message = enveloped_data.Encrypt(pycades.CADESCOM_ENCODE_BASE64)
print("=== Зашифрованное сообщение ===")
print(encrypted_message[:100] + "...")
# Расшифрование данных
# Для расшифрования необходим закрытый ключ одного из получателей
decrypt_data = pycades.EnvelopedData()
decrypt_data.Decrypt(encrypted_message)
# Получение расшифрованного содержимого
decrypted_content = decrypt_data.Content
print(f"Расшифрованное сообщение: {decrypted_content}")
# Проверка корректности расшифрования
assert decrypted_content == "Секретное сообщение для шифрования с русскими буквами", \
"Ошибка расшифрования"
print("Данные успешно расшифрованы")
store.Close()
```