waptcrypto module

exception waptcrypto.EWaptBadCertificate[source]

Bases: waptcrypto.EWaptCryptoException

exception waptcrypto.EWaptBadKeyPassword[source]

Bases: waptcrypto.EWaptCryptoException

exception waptcrypto.EWaptCertificateBadSignature[source]

Bases: waptcrypto.EWaptBadCertificate

exception waptcrypto.EWaptCertificateExpired[source]

Bases: waptcrypto.EWaptBadCertificate

exception waptcrypto.EWaptCertificateRevoked[source]

Bases: waptcrypto.EWaptBadCertificate

exception waptcrypto.EWaptCertificateUnknownIssuer[source]

Bases: waptcrypto.EWaptBadCertificate

exception waptcrypto.EWaptCertificateUntrustedIssuer[source]

Bases: waptcrypto.EWaptBadCertificate

exception waptcrypto.EWaptCryptoException[source]

Bases: exceptions.Exception

exception waptcrypto.EWaptEmptyPassword[source]

Bases: waptcrypto.EWaptCryptoException

exception waptcrypto.EWaptMissingCertificate[source]

Bases: waptcrypto.EWaptCryptoException

exception waptcrypto.EWaptMissingPrivateKey[source]

Bases: waptcrypto.EWaptCryptoException

waptcrypto.NOPASSWORD_CALLBACK(*args)[source]
class waptcrypto.SSLCABundle(cert_pattern_or_dir=None, callback=None, certificates=None)[source]

Bases: waptutils.BaseObjectClass

BEGIN_CERTIFICATE = '-----BEGIN CERTIFICATE-----'
BEGIN_CRL = '-----BEGIN X509 CRL-----'
BEGIN_KEY = '-----BEGIN ENCRYPTED PRIVATE KEY-----'
END_CERTIFICATE = '-----END CERTIFICATE-----'
END_CRL = '-----END X509 CRL-----'
END_KEY = '-----END ENCRYPTED PRIVATE KEY-----'
add_certificates(certificates)[source]

Add a list of certificates to the bundle and index them.

Returns:list of SSLCertificates actually added
add_crl(crl)[source]

Replace or Add pem encoded CRL

add_pem(pem_data=None, load_keys=False, pem_filename=None)[source]

Parse a bundle PEM with multiple certificates, CRL and keys. If key needs to be decrypted, password callback property must be assigned.

Returns:self
Return type:SSLCABundle
add_pems(cert_pattern_or_dir='*.crt', load_keys=False)[source]
as_pem(with_keys=True, password=None)[source]
certificate(fingerprint)[source]
certificate_chain(certificate=None, fingerprint=None)[source]

return certificates chain from certificate, without checking certificate signatures and validity

Returns:list of certificates starting with leaf up to root CA.
Return type:list
certificate_for_cn(cn)[source]

Handles wildcards cn…

certificate_for_subject_hash(subject_hash)[source]
certificate_for_subject_key_identifier(subject_key_identifier)[source]
certificates(valid_only=False)[source]
check_certificates_chain(cert_chain, verify_expiry=True, verify_revoke=True, allow_pinned=True)[source]

Check that first certificate in cert_chain is approved by one of the CA certificate from this bundle.

If intermdiate issuers can not be found in this ca bundle, try to get them from supplied cert_chain.

Parameters:
  • cert_chain (list) – list of certificates. first one is starting point. The other ones are used if None can be found in cabundle
  • verify_expiry (bool) – Check if certificates expiry dates are okay relative to today.
  • verify_revoke (bool) – Check if certificate is not in the CRLs (if certificate contains crl location URL) CRL must have been already retrieved using update_crl.
  • allow_pinned (bool) – If True, accept certificate if it is in trusted certificates, even if we don’t know the issuer.
Returns:

SSLCertificate chain of trusted cert

Return type:

(list)

check_if_revoked(cert)[source]

Raise exception if certificate has been revoked before now

clear()[source]
crl_for_authority_key_identifier(authority_key_identifier)[source]
crl_for_issuer_subject_hash(issuer_subject_hash)[source]
download_issuer_certs(force=False, for_certificates=None)[source]

Download and add CA certs using authorityInfoAccess access_location No check is attempted on cert signatures.

Returns:of missing downloaded SSLCertificates
Return type:list
is_known_issuer(certificate, include_self=True)[source]

Check if certificate is issued by one of this certificate bundle CA and check certificate signature. Return top most CA.

Top most CA should be trusted somewhere…

Parameters:
  • certificate – certificate to check
  • include_self – if certificate is in bunclde, accept it (pining)
Returns:

issuer certificate or None

Return type:

SSLCertificate

is_valid_certificate(certificate, check_revoke=True)[source]

Check if certificate valid using ssl store context

Parameters:
  • certificate – certificate to check
  • include_self – if certificate is in bunclde, accept it (pining)
Returns:

issuer certificate or None

Return type:

SSLCertificate

issuer_cert_for(certificate)[source]
key(modulus, password)[source]
keys()[source]
matching_certs(key, ca=None, code_signing=None, valid=True)[source]
md = 'sha256'
save_as_pem(filename, with_keys=True, password=None)[source]

Save the RSA private key as a PEM encoded file

Optionnaly, encypt the key with a password.

Parameters:
  • filename (str) – filename of pem file to create. If not provided use the filename from self.
  • password (str) – password. If None, don’t encrypt the key. if password is unicode, it is encoded in utf8 first.
update_crl(force=False, for_certificates=None, cache_dir=None, timeout=2.0)[source]

Download and update all crls for certificates in this bundle or for certificates in for_certificates list

Returns:list of downloaded / updated CRL
Return type:list
class waptcrypto.SSLCRL(filename=None, pem_data=None, der_data=None)[source]

Bases: waptutils.BaseObjectClass

as_der()[source]
as_pem()[source]
authority_key_identifier

Identify the authrority which has signed the certificate

crl
extensions

CRL extensions

Returns:dict
is_revoked(cert)[source]
issuer
issuer_cn
issuer_dn
issuer_subject_hash
last_update
next_update
revoked_certs()[source]
save_as_pem(filename=None)[source]
verify_signature_with(cabundle=None)[source]

Check validity of CRL signature

Args;
cabundle: bundle of CA certificates
Returns:certificate chain
Return type:list
class waptcrypto.SSLCertificate(crt_filename=None, crt=None, crt_string=None, ignore_validity_checks=False)[source]

Bases: waptutils.BaseObjectClass

Hold a X509 public certificate

as_X509()[source]

Return pycrypto style X509 object

as_pem()[source]
authority_key_identifier

Identify the authority which has signed the certificate

build_certificate_from_csr(csr, ca_signing_key, validity_duration=365)[source]
Parameters:
Returns:

SSLCertificate

cn
crl_urls()[source]

retruns list of URL where to get CRL for the Authority which has signed this certificate

crt

Return cryptopgraphy.Certificate instance

digest(md='sha256')[source]

Return a fingerprint in human redeable hexadecimal

Parameters:md – hash algorithm for fingerprint
Returns:hex encoded digest of fingerprint of certificate
Return type:str
encrypt(content)[source]

Encrypt a (small) message will can be decrypted with the public key

encrypt_fernet(content)[source]

Encrypt content with fernet symetric algo

create a fernet key, encrypt it using RSA encrypt data using fernet key return bytes with header, encrypted fernet key, and encrypted fernet data

fernet : 128-bit AES in CBC mode and PKCS7 padding, with HMAC using SHA256 for authentication

Parameters:content (bytes) – data to encrypt
Returns:
starts with ‘RSAFERNET’, then rsa key length (base10) on 3 chars
then rsa encrypted fernet key, then fernet encrypted data
Return type:crypted_data (bytes)
extensions

Returns certificates extensions as a dict

Returns:dict
fingerprint

Get hex endoded sha256 fingerprint

from_X509(x509_cert)[source]

Initialize certificate from pycrypto style X509 object

get_fingerprint(md='sha256')[source]

Get raw bytes fingerprint

has_usage(usage)[source]

Return usage if certificate has the requested usage

Parameters:usage (str) – ca or code_signing
is_ca

Return Tue if certificate has CA – TRUE baisc contraints

is_code_signing

Return True if certificate has ‘Code Signing’ in its extendedKeyUsage

is_valid()[source]

Check validity of certificate not before / not after

issuer

Return issuer as a dict of x509 name attributes

Returns:dict
issuer_cert_urls()[source]

returns URL where to get Issuer cert directly

issuer_cn
issuer_dn
issuer_hash
issuer_subject_hash
key_usage
match_key(key)[source]

Check if certificate matches the given private key

matching_key_in_dirs(directories=None, password_callback=None, private_key_password=None, fpcall=False)[source]

Return the first SSLPrivateKey matching this certificate

Parameters:directories (list) – list of directories to look for pem encoded private key files if None, look in the same directory as certificate file.
Returns:or None if nothing found.
Return type:SSLPrivateKey
>>> crt = SSL
modulus
not_after
not_before
organisation
public_cert_filename

Return filename if certificate was/will be loaded from a file

rsa

Return public RSA key

save_as_pem(filename=None)[source]
serial_number

Serial number of the certificate, which is used by revocation process

subject

Returns subject of the certificate as a Dict

subject_alt_names

Other names of the subject (in addition to cn)

subject_dn
subject_hash
subject_key_identifier

Identify the certificate

verify_claim(claim, max_age_secs=None, required_attributes=[])[source]

Verify a simple dict signed with SSLPrivateKey.sign_claim

Parameters:claim (dict) – with keys signature,signed_attributes,signer,signature_date
Returns:signature_date,signer,verified_by(cn)
Return type:dict
>>> key = SSLPrivateKey('c:/private/150.pem')
>>> crt = SSLCertificate('c:/private/150.crt')
>>> action = dict(action='install',package='tis-7zip')
>>> action_signed
    {'action': None,
     'package': None,
     'signature': 'jSJbX3sPmiEBRxN3Sue4fTSlJ2Q6llUSOIkleCm4NyFQlSc0KvLKbtlmHxvYV7mPW3TDYjfhkuQSG0ZfQQmo0r+zcA9ZL075P/vNLkxwElOYacMtBBObsxhPU7DKc4AdQMorgSfSEpW4a/Zq5VPJy9q6vBJxSzZjnHGmuPYlfQKuedP1dY6ifCrcAelKEZOKZl5LJl6e0NHeiXy3+3e4bm8V2VtDPCbvVKtIMRgA5qtDDrif3IauwzUyzEpnC0d229ynz6LAj5WdZR32HtV0g5aJ5ye5rQ+IAcGJSbxQ3EJZQhZy1wZ6WUVsF9/mXLbR/d1xRl9M0CqI+8eUvQWD2g==',
     'signature_date': '20170606-163401',
     'signed_attributes': ['action', 'package'],
     'signer': '150',
     'signer_fingerprint': '88654A5A946B8BFFFAC7F61A2E21B7F02168D5E4'}
>>> action_signed = key.sign_claim(action,certificate=crt)
>>> print crt.verify_claim(action_signed)
{'signer': '150', 'verified_by': '150', 'signature_date': '20170606-163401'}
verify_content(content, signature, md='sha256', block_size=1048576)[source]

Check that the signature matches the content

Parameters:
  • content (str) – content to check. if not str, the structure will be converted to json first
  • signature (str) – ssl signature of the content
Returns:

subject (CN) of current certificate or raise an exception if no match

Return type:

str

Raises SSLVerifyException

verify_old(CAfile, check_errors=True)[source]

Check validity of certificate against list of CA and validity

Raise error if not OK

verify_signature_with(cabundle=None)[source]

Check validity of certificates signature along the whole certificates chain

Issuer certificates must have the CA constraint. Issuer is found using hash of issuer_subject and subject bytes.

Args;
cabundle: bundle of CA certificates, or SSLCertificate od list of certificates
if None, get bindle from certifi default list.
Returns:certificate chain
Return type:list
class waptcrypto.SSLCertificateSigningRequest(csr=None, csr_filename=None, csr_pem_string=None)[source]

Bases: waptutils.BaseObjectClass

as_pem()[source]
save_as_pem(filename)[source]
class waptcrypto.SSLPrivateKey(filename=None, pem_data=None, callback=None, password=None)[source]

Bases: waptutils.BaseObjectClass

as_pem(password=None)[source]

Return private key as a PEM str

Args;
password (str): password to use to encrypt the key.
Returns:pem encoded RSA Private key.
Return type:str
build_csr(cn=None, organizational_unit=None, organization=None, locality=None, country=None, dnsname=None, email=None, is_ca=False, is_code_signing=None, key_usages=['digital_signature', 'content_commitment', 'key_cert_sign', 'data_encipherment'])[source]

Build a certificate signing request with self public key and supplied attributes,

Parameters:
  • is_ca (bool) – certificate is a CA root or intermediate or self-signed if None, default to True is ca_signing_cert is None
  • is_code_signing (bool) – subject can sign code if None, default to (not is_ca)
  • dnsname (str) – Witll be added as an DNS SubjectAlternativeName.
  • key_usages (list of str) – list of certificate / key usage targets.
Returns:

SSLCertificateSigningRequest

build_sign_certificate(ca_signing_key=None, ca_signing_cert=None, cn=None, organizational_unit=None, organization=None, locality=None, country=None, dnsname=None, email=None, is_ca=None, is_code_signing=None, key_usages=['digital_signature', 'content_commitment', 'key_cert_sign', 'data_encipherment'], crl_url=None, issuer_cert_url=None)[source]

Build a certificate with self public key and supplied attributes, and sign it with supplied ca_signing_key.

To self sign the certificate, put None for ca_signing_key and ca_signing_cert

Parameters:
  • ca_signing_key (SSLPrivateKey) –
  • ca_signing_cert (SSLCertificate) –
  • is_ca (bool) – certificate is a CA root or intermediate or self-signed if None, default to True is ca_signing_cert is None
  • is_code_signing (bool) – subject can sign code if None, default to (not is_ca)
  • dnsname (str) – Witll be added as an DNS SubjectAlternativeName.
  • key_usages (list of str) – list of certificate / key usage targets.
Returns:

self

create(bits=2048)[source]

Create a RSA key pair

decrypt(content)[source]

Decrypt a message encrypted with the public key. For small messages only.

decrypt_fernet(crypted_data)[source]

Decrypt bytes which has been crypted by SSLCertificate.encrypt_fernet the fernet symetric key is decrypted using RSA payload is decrypted using fernet key

Parameters:crypted_data (bytes) – starts with ‘RSAFERNET’, then rsa key length (base10) on 3 chars then rsa encrypted fernet key, then fernet encrypted data
Returns:decrypted data
Return type:bytes
load_key_data(pem_data)[source]

Load RSA structure with the provided pem_dat

Args;
pem_data (str) : base64 PEM style encoded RSA private key
Returns:None
match_cert(crt)[source]

Check if provided public certificate matches the current private key

matching_certs(cert_dir=None, ca=None, code_signing=None, valid=None)[source]

Returns list of certificates in cert_dir with public key matching this private_key.

Parameters:
  • cert_dir (str) – directory path where to search for .crt, .der or .pem X509 certificates files
  • ca (bool) – if not None, returns only certificates which ahev the CA constraint set or not
  • code_signing (bool) – if not None, return only certificates which have the code_signing attribute or not
  • valid (bool) – if True, return only certificates which are calid (not before / not after attibutes check)
Returns:

list of SSLCertificate matching the key

Return type:

list

modulus
public_key()[source]

Return the RSA public key object

Returns:RSAPublicKey
public_key_as_openssh()[source]

Return public key as a PEM str

Returns:pem encoded RSA public key.
Return type:str
public_key_as_pem()[source]

Return public key as a PEM str

Returns:pem encoded RSA public key.
Return type:str
rsa

access to RSA keys

>>> key = SSLPrivateKey('c:/private/tranquilit2.pem')
>>> key.rsa
Please type the password to decrypt the private key
<cryptography.hazmat.backends.openssl.rsa._RSAPrivateKey object at 0x040ECE70>
>>> key.rsa.public_key()
<bound method _RSAPrivateKey.public_key of <cryptography.hazmat.backends.openssl.rsa._RSAPrivateKey object at 0x040ECE70>>
>>> key.rsa.private_bytes()
<bound method _RSAPrivateKey.private_bytes of <cryptography.hazmat.backends.openssl.rsa._RSAPrivateKey object at 0x040ECE70>>
save_as_pem(filename=None, password=None)[source]

Save the RSA private key as a PEM encoded file

Optionnaly, encypt the key with a password.

Parameters:
  • filename (str) – filename of pem file to create. If not provided use the filename from self.
  • password (str) – password. If None, don’t encrypt the key. if password is unicode, it is encoded in utf8 first.
sign_claim(claim, attributes=None, certificate=None)[source]

Sign a set of attributes of a dict

Parameters:
  • claim (dict) – data structure to sign
  • attributes (list) – list of attributes to include in signature
  • certificate (list) – certificate chain of signer
Returns:

same as claim with additional signature attributes

’signed_attributes’,’signer’,’signature_date’,’signer_certificate’

Return type:

dict

sign_content(content, md='sha256', block_size=1048576)[source]

Sign content with the private_key, return the signature

If content is not a raw string, it is first encoded in json or utf8

Parameters:
  • content (str, list or dict) – content to sign
  • md (str) – lessage digest type to use
  • clock_size (int) – unused
Returns:

signature

Return type:

bytes

exception waptcrypto.SSLVerifyException[source]

Bases: waptcrypto.EWaptCryptoException

waptcrypto.check_key_password(key_filename, password=None)[source]

Check if provided password is valid to read the PEM private key

Parameters:password (str) – or None if key is not encrypted.
waptcrypto.default_pwd_callback(*args)[source]

Default password callback for opening private keys.

waptcrypto.get_hash_algo(md='sha256')[source]
waptcrypto.get_peer_cert_chain_from_server(url)[source]

Returns list of SSLCertificates from initial handshake of https server Add certificates to current SSLCAchain First certificate is certificate for URL’s FQDN, next are intermediate ones.

waptcrypto.get_pem_server_certificate(url, save_to_file=None)[source]

Retrieve single certificate from ssl server for further checks

Returns:pem encoded data
Return type:str
waptcrypto.hash_for_file(fname, block_size=1048576, md='sha256')[source]
waptcrypto.hexdigest_for_data(data, md='sha256')[source]
waptcrypto.hexdigest_for_file(fname, block_size=1048576, md='sha256')[source]
waptcrypto.read_in_chunks(f, chunk_size=131072)[source]

Lazy function (generator) to read a file piece by piece. Default chunk size: 128k.

waptcrypto.sha1_for_data(data)[source]
waptcrypto.sha1_for_file(fname, block_size=1048576)[source]
waptcrypto.sha256_for_data(data)[source]
waptcrypto.sha256_for_file(fname, block_size=1048576)[source]