11. windows.crypto – CryptoAPI

The windows.crypto module offers some wrappers arround the CryptoAPI.

The main goal of this module (for now) is providing simple encryption/decryption methods.

11.1. Encryption

Note

See sample Encryption demo

11.1.1. encrypt

windows.crypto.encrypt(cert_or_certlist, msg, algo=szOID_NIST_AES256_CBC('2.16.840.1.101.3.4.1.42'), initvector=GenerateInitVector())[source]

Encrypt msg one or many Certificate using algo with the initial vector initvector.

If geninitvector is left as it is, it will generate a random one.

Algorithms supported by GenerateInitVector are:

  • szOID_OIWSEC_desCBC
  • szOID_RSA_DES_EDE3_CBC
  • szOID_NIST_AES128_CBC
  • szOID_NIST_AES192_CBC
  • szOID_NIST_AES256_CBC
Parameters:cert_or_certlist (Certificate | [Certificate]) – One or many Certificate used to encrypt the msg
Returns:bytearray: The encrypted message

11.1.2. decrypt

windows.crypto.decrypt(cert_store, encrypted)[source]

Try to decrypt the encrypted msg with any certificate in cert_store.

If there is no certificate able to decrypt the message WinproxyError(winerror=0x8009200c) is raised.

Parameters:cert_store (CertificateStore) –
Returns:str: The decrypted message

11.1.3. import_pfx

windows.crypto.import_pfx(pfx, password=None, flags=37376L)[source]

Import the file pfx with the password.

default flags = PKCS12_NO_PERSIST_KEY | CRYPT_USER_KEYSET.

PKCS12_NO_PERSIST_KEY tells CryptoAPI to NOT save the keys in a on-disk container.

Returns:CertificateStore

11.2. Certificate

Warning

The classes described here are still under test and possible rewrite/refactor.

The classes, methods and properties described here will problably change as I haven’t yet had the time to try it out in real cases and figure out the final look of the API I want to do.

Note

See sample Certificate demo

11.2.1. Certificate

class windows.crypto.Certificate[source]

Bases: windows.generated_def.winstructs._CERT_CONTEXT

Represent a Certificate

chains

The list of chain context available for this certificate. Each elements of this list is a list of Certificate that should go from the self certificate to a trusted certificate.

Type:[[Certificate]] – A list of chain (list) of Certificate
distinguished_name

The distinguished name (DN) of the certificate.

Example:

>>> x
<Certificate "Microsoft Windows Production PCA 2011" serial="61 07 76 56 00 00 00 00 00 08">
>>> x.distinguished_name
'C=US, S=Washington, L=Redmond, O=Microsoft Corporation, CN=Microsoft Windows Production PCA 2011'
Type:str
duplicate()[source]

Duplicate the certificate by incrementing the internal refcount. (see CertDuplicateCertificateContext)

note: The object returned is self

Returns:Certificate
encoded

The encoded certificate.

Type:bytearray
classmethod from_buffer(data)[source]

Create a Certificate from the buffer data

Returns:Certificate
classmethod from_file(filename)[source]

Create a Certificate from the file filename

Returns:Certificate
get_name(nametype=CERT_NAME_SIMPLE_DISPLAY_TYPE(0x4), param_type=0, flags=0)[source]

Retrieve the subject or issuer name of the certificate. See CertGetNameStringA

Returns:str
get_property(prop)[source]

TODO: DOC :D + auto-type ?

issuer

The name of the certificate’s issuer.

Type:str
name

The name of the certificate.

Type:str
properties

The properties of the certificate

Type:[int or Flag] – A list of property ID
raw_serial

The raw serial number of the certificate.

Type:[int]: A list of int 0 <= x <= 255
serial

The string representation of the certificate’s serial.

Type:str
store

The certificate store that contains the certificate

Type:CertificateStore
thumbprint

The thumbprint of the certificate (which is the sha1 of the encoded cert).

Example:

>>> x
<Certificate "YOLO2" serial="6f 1d 3e 7d d9 77 59 a9 4c 1c 53 dc 80 db 0c fe">
>>> x.thumbprint
'E2 A2 DB 76 A1 DD 8E 70 0D C6 9F CB 71 CF 29 12 C6 D9 78 97'
Type:str
version

The version number of the certificate

Type:int

11.2.2. CertificateStore

class windows.crypto.CertificateStore[source]

A certificate store

add_certificate(certificate)[source]

Add a certificate to the store

certs

The list of certificates in the store

Type:[Certificate] – A list of certificate
find(issuer, serialnumber)[source]

Return the certificate that match issuer and serialnumber

Returns:CertificateNone if certificate is not found
classmethod from_file(filename)[source]

Create a new CertificateStore from filename

classmethod from_system_store(store_name)[source]

Create a new CertificateStore from system store store_name (see System Store Locations)

classmethod new_in_memory()[source]

Create a new temporary CertificateStore in memory

value

current value

11.2.3. CryptObject

class windows.crypto.CryptObject(filename, content_type=CERT_QUERY_CONTENT_FLAG_ALL(0x3ffe))[source]

Extract information from an CryptoAPI object. (see CryptQueryObject)

Current main use is extracting the signers certificates from a PE file.

cert_store = None

The CertificateStore that includes all of the certificates, CRLs, and CTLs in the object

content_type = None

The type of the opened message

crypt_msg = None

The CryptMessage for any PKCS7 content in the object

signers_and_certs

The list of signer info and certificates signing the object.

Return type:[(CMSG_SIGNER_INFO, Certificate)]

Note

CMSG_SIGNER_INFO might be changed to a wrapping-subclass.

11.2.4. CryptMessage

class windows.crypto.CryptMessage[source]

Represent a PKCS #7 message (see Low-level Message Functions)

certs

The list of Certificate embded in the message

classmethod from_buffer(object, offset=0) → C instance[source]

create a C instance from a writeable buffer

get_cert(index=0)[source]

Return embded Certificate number index.

Note

Not all embded certificate are directly used to sign the CryptObject.

get_recipient_data(index=0)[source]

TODO: DOC

get_signer_data(index=0)[source]

Returns the signer informations for signer nb index

Returns:CMSG_SIGNER_INFO
nb_cert

The number of certificate embded in the CryptObject

Type:int
nb_recipient

TODO: DOC

nb_signer

The number of signers for the CryptObject

Type:int
recipients

TODO: DOC

signers

The list of CMSG_SIGNER_INFO embed in the message

value

current value

11.2.5. CryptContext

class windows.crypto.CryptContext(pszContainer=None, pszProvider=None, dwProvType=0, dwFlags=0, retrycreate=False)[source]

A context manager arround CryptAcquireContextW & CryptReleaseContext

Note

see usage in sample Encryption demo (function genkeys)

contents

the object this pointer points to (read-write)

11.3. Generating componants

This module is used to generate selfsigned-certificates / keypair and pfx file.

Note

See genkeys() in the sample Encryption demo

11.3.1. generate_selfsigned_certificate

windows.crypto.generation.generate_selfsigned_certificate(name='CN=DEFAULT', prov=None, key_info=None, flags=0, signature_algo=None)[source]

Generate a selfsigned certificate.

See CertCreateSelfSignCertificate

Returns:windows.crypto.Certificate

11.3.2. generate_key

windows.crypto.generation.generate_key(prov, keytype=AT_KEYEXCHANGE(0x1), flags=CRYPT_EXPORTABLE(0x1))[source]

Generate a keypair if type keytype.

Returns:HCRYPTKEY

11.3.3. generate_pfx

windows.crypto.generation.generate_pfx(hstore, password=None)[source]

Generate a pfx protected by password contaning the certificates in hstore

Returns:bytearray – The raw PFX