cryptopyutils package

Subpackages

Submodules

cryptopyutils.cert module

cert.py - x509 Certificates

Class:

  • Commonx509: Build certificate attribute names and name attributes

  • Certificate : Load, generate, save x509 Certificates

class cryptopyutils.cert.Certificate(**kwargs)[source]

Bases: Base

Certificate Object - extends Base

Usage:

  • initialize : c = Certificate(private_key=PrivateKey())

  • generate cert : c.gen()

  • generate self-signed cert : c.gen_self_signed()

  • get certificate object : c.cert

  • save cert: c.save(filepath)

  • load cert: c.load(filepath)

property cert

Get the cert attribute

Returns

An instance of Certificate from Cryptography

Return type

Cryptography Certificate

gen(issuer=None, subject=None, dns_names=None, ip_addresses=None, expiration_days=None, critical=None, hash_alg=None, cert_auth=None, path_length=None)[source]

Generate a x509 certificate

Parameters
  • issuer – dict(str, optional): The issuer informations needed to generate

  • certificate. (the) – Defaults to None.

  • subject – dict(str, optional): The subject informations needed to generate

  • certificate. – Defaults to None.

  • dns_names (list(str), optional) – A list of DNS Names. Defaults to None.

  • ip_addresses – list(str, optional): A list of IP addresses. Defaults to None.

  • expiration_days (int, optional) – Number of days until the certificate expires. Defaults to None.

  • critical (bool, optional) – Set to True if the extension must be understood and handled by whoever reads the certificate. Defaults to None.

  • hash_alg (str, optional) – The Hash algorithm. Defaults to None.

  • cert_auth (bool, optional) – Whether the certificate can sign certificates. Defaults to None.

  • path_length (int, optional) – The maximum path length for certificates subordinate to this certificate. This attribute only has meaning if cert_auth is true. If cert_auth is true then a path length of None means there’s no restriction on the number of subordinate CAs in the certificate chain. If it is zero or greater then it defines the maximum length for a subordinate CA’s certificate chain. For example, a path_length of 1 means the certificate can sign a subordinate CA, but the subordinate CA is not allowed to create subordinates with cert_auth set to true. Defaults to None.

gen_self_signed(subject=None, dns_names=None, ip_addresses=None, expiration_days=None, critical=True, hash_alg=None, certh_auth=False, path_length=None)[source]

Generate a self signed x509 certificate

Parameters
  • subject – dict(str, optional): The issuer informations needed to generate the certificate. Subject also is the issuer for self-signed certificates. Defaults to None.

  • subject – dict(str, optional): The subject informations needed to generate the certificate. Defaults to None.

  • dns_names (list(str, optional) – A list of DNS Names. Defaults to None.

  • ip_addresses – list(str, optional): A list of IP addresses. Defaults to None.

  • expiration_days (int, optional) – Number of days until the certificate expires. Defaults to None.

  • critical (bool, optional) – Set to True if the extension must be understood and handled by whoever reads the certificate. Defaults to True, for self signed.

  • hash_alg (str, optional) – The Hash algorithm. Defaults to None.

  • cert_auth (bool, optional) – Whether the certificate can sign certificates. Defaults to False for self-signed certificate.

  • path_length (int, optional) – The maximum path length for certificates subordinate to this certificate. This attribute only has meaning if cert_auth is true. If cert_auth is true then a path length of None means there’s no restriction on the number of subordinate CAs in the certificate chain. If it is zero or greater then it defines the maximum length for a subordinate CA’s certificate chain. For example, a path_length of 1 means the certificate can sign a subordinate CA, but the subordinate CA is not allowed to create subordinates with cert_auth set to true. Defaults to None, for self-signed

hash_fingerprint_pem_cert(path, hash_alg=None, b64output=False)[source]

Get the fingerprint of a base64 PEM certificate based on a hash function

Parameters
  • path (str) – path to the base64 encoded PEM certificate file

  • hash_alg (HashAlgorithm, optional) – Defaults to None.

  • b64output (bool, optional) – If True, output is base64 format. If false, output is represented as heximals. Defaults to False

load(path, encoding=None)[source]

Load the x509 certificate from the disk

Parameters
  • path (str) – The file path where the certificate is saved.

  • encoding (str, optional) – Encoding PEM or DER. Defaults to None.

load_der(path)[source]

Load the DER x509 certificate from the disk

Parameters

path (str) – The file path where the certificate is saved.

load_pem(path)[source]

Load the PEM x509 certificate from the disk

Parameters

path (str) – The file path where the certificate is saved.

property private_key

Get the private_key attribute

Returns

An instance of PrivateKey

Return type

PrivateKey

save(path, file_mode=None, encoding=None, force=False)[source]

Write our x509 certificate out to disk

Parameters
  • path (str) – The file path where the certificate will be saved.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • encoding (str, optional) – Encoding PEM or DER. Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

save_der(path, file_mode=None, force=False)[source]

Write our DER x509 certificate out to disk

Parameters
  • path (str) – The file path where the certificate will be saved.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced to overwrite.

Return type

bool

save_pem(path, file_mode=None, force=False)[source]

Write our PEM x509 certificate out to disk

Parameters
  • path (str) – The file path where the certificate will be saved.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

cryptopyutils.config module

config.py - Configuration file

Configuration of defaults

You can update the config according to your needs.

class cryptopyutils.config.AsymConfig(**kwargs)[source]

Bases: ProjConfig

AsymConfig class - Asymmetric Configuration class - extends ProjConfig

set_ssl_dir(path=None)[source]

Set the SSL directory

Parameters

path (str, optional) – Path to the SSL directory. Defaults to None.

Returns

The path to the ssl directory

Return type

str

class cryptopyutils.config.Base(**kwargs)[source]

Bases: object

Base class

copy(source)[source]

Copy attributes from a source object

Parameters

source (obj) – source object

Returns

self

Return type

obj

class cryptopyutils.config.CSRConfig(**kwargs)[source]

Bases: X509Config

CSRConfig class - x509 CSR Configuration - extends x509Config

set_csr_dir(path=None)[source]

Set the SSL CSR directory

Parameters

(str (path) – optional): Path to the SSL CSR directory. Defaults to None.

class cryptopyutils.config.CertConfig(**kwargs)[source]

Bases: X509Config

CertConfig class - x509 Certificate Configuration - extends x509Config

set_cert_dir(path=None)[source]

Set the SSL Certificate directory

Parameters

(str (path) – optional): Path to the SSL certificate directory. Defaults to None.

class cryptopyutils.config.PasswordConfig(**kwargs)[source]

Bases: Base

PasswordConfig class - Password Configuration class - extends Base

Parameters
  • hash_algorithm (str) – the name of the hash algorithm. Defaults to SHA-256.

  • salt_length (int) – Secure values are 16 (128-bits) or longer and randomly generated. Defaults to 16.

  • length (int) – Maximum is (232 - 1) * algorithm.digest_size. Defaults to 32.

  • iterations (int) – hash function. This can be used to control the length of time the operation takes. Higher numbers help mitigate brute force attacks against derived keys. Defaults to 390000.

class cryptopyutils.config.PrivateKeyConfig(**kwargs)[source]

Bases: Base

PrivateKeyConfig class - Private Key Configuration - extends AsymConfig

set_key_dir(path=None)[source]

Set the SSL private key directory

Parameters

(str (path) – optional): Path to the SSL private key directory. Defaults to None.

class cryptopyutils.config.ProjConfig(**kwargs)[source]

Bases: Base

Projconfig class - Project Configuration - extends SysConfig

class cryptopyutils.config.PublicKeyConfig(**kwargs)[source]

Bases: Base

PublicKeyConfig initiator - Public Key Configuration - extends AsymConfig

set_key_dir(path=None)[source]

Set the SSL public key directory

Parameters

(str (path) – optional): Path to the SSL public key directory. Defaults to None.

class cryptopyutils.config.SSHKeyPairConfig(**kwargs)[source]

Bases: Base

SSHKeyPairConfig class - Configuration for SSH Key Pair

set_host_dir(path=None)[source]

Set the SSH host directory

Parameters

(str (path) – optional): Path to the SSH host directory. Defaults to None.

set_user_dir(path=None)[source]

Set the SSH user directory

Parameters

(str (path) – optional): Path to the SSH user directory. Defaults to None.

class cryptopyutils.config.SysConfig(**kwargs)[source]

Bases: Base

SysConfig class - System Configuration - system information - extends Base

class cryptopyutils.config.X509Config(**kwargs)[source]

Bases: AsymConfig

X509Config class - x509 Configuration - extends AsymConfig

cryptopyutils.csr module

csr.py - Certificate Signing Request (CSR)

Class:

  • CSR : x509 CSR object

class cryptopyutils.csr.CSR(**kwargs)[source]

Bases: Base

CSR Object extends Base

Usage:

  • initialize : c = CSR() or c = CSR(private_key=PrivateKey())

  • generate csr : c.gen()

  • get csr object : c.csr

  • save csr: c.save(filepath)

  • load keycsr: c.load(filepath)

property csr

Get the CSR attribute

Returns

An instance of CSR from Cryptography.

Return type

Cryptography CSR

gen(challenge_password, subject=None, dns_names=None, ip_addresses=None, hash_alg=None)[source]

Generate a x509 CSR

Parameters
  • challenge_password (str or bytes) – The secret shared with the certificate issuer.

  • UTF8. (String will be encoded in) –

  • subject – dict(str, optional): The subject informations needed to generate the CSR. Defaults to None.

  • dns_names (list(str), optional) – A list of DNS Names. Defaults to None.

  • ip_addresses – list(str, optional): A list of IP addresses. Defaults to None.

  • hash_alg (str, optional) – The Hash algorithm. Defaults to None.

load(path, encoding=None)[source]

Load the CSR the disk

Parameters
  • path (str) – The file path where the CSR is saved.

  • encoding (str, optional) – Encoding PEM or DER. Defaults to None.

load_der(path)[source]

Load the DER x509 CSR from the disk

Parameters

path (str) – The file path where the CSR is saved.

load_pem(path)[source]

Load the PEM x509 CSR from the disk

Parameters

filepath (str) – The file path where the CSR is saved.

property private_key

Get the private_key attribute

Returns

An instance of PrivateKey.

Return type

PrivateKey

save(path, file_mode=None, encoding=None, force=False)[source]

Write our x509 CSR out to disk

Parameters
  • path (str) – The file path where the CSR will be saved.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • encoding (str, optional) – Encoding PEM or DER. Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

save_der(path, file_mode=None, force=False)[source]

Write our DER x509 CSR out to disk

Parameters
  • path (str, optional) – The file path where the CSR will be saved.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

save_pem(path, file_mode=None, force=False)[source]

Write our PEM x509 CSR out to disk

Parameters
  • path (str) – The file path where the CSR will be saved.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

cryptopyutils.dirs module

dir.py - Directory manipulations

cryptopyutils.dirs.mkdir(folder)[source]

Creates the folder

Parameters

dir (str) – A directory path to create

cryptopyutils.dirs.prep_dir_path(path)[source]

Prepare a directory path by expanding and normalizing it

Parameters

path (str) – directory path

cryptopyutils.dirs.rmdir(folder)[source]

Removes the folder

Parameters

dir (str) – A directory path to remove

cryptopyutils.files module

files.py - Files manipulation and filepaths generation

cryptopyutils.files.cer(host_dns, out_dir=None)[source]

Generate the filepath for a Certificate with .cer extension

Parameters
  • host_dns (str) – The FDQN of the host.

  • out_dir (str, optional) – The directory. Defaults to None.

Returns

The filepath.

Return type

str

cryptopyutils.files.crt(host_dns, out_dir=None)[source]

Generate the filepath for a Certificate with .crt extension

Parameters
  • host_dns (str) – The FDQN of the host.

  • out_dir (str, optional) – The directory. Defaults to None.

Returns

The filepath.

Return type

str

cryptopyutils.files.csr(host_dns, out_dir=None)[source]

Generate the filepath for a CSR

Parameters
  • host_dns (str) – The FDQN of the host.

  • out_dir (str, optional) – The directory. Defaults to None.

Returns

The filepath.

Return type

str

cryptopyutils.files.der(host_dns, out_dir=None)[source]

Generate the filepath for a DER private key file

Parameters
  • host_dns (str) – The FDQN of the host.

  • out_dir (str, optional) – The directory. Defaults to None.

Returns

The filepath.

Return type

str

cryptopyutils.files.file_exists(path)[source]

Determine if the file exists

Parameters

path (str) – the filepath.

Returns

True if exists, else False.

Return type

bool

cryptopyutils.files.generate(host_dns, out_dir=None, ext='pem')[source]

Generate the filepath for a private key, public key, certificate, csr …

Parameters
  • host_dns (str) – The FDQN of the host.

  • out_dir (str, optional) – The directory. Defaults to None.

  • ext (str, optional) – The file extension. Typically crt for certificates, csr for CSR. Defaults to pem.

Returns

The filepath.

Return type

str

cryptopyutils.files.get_chmod(path)[source]

Returns the mode of a file using chmod

Parameters

path (str) – the file path.

Returns

the file mode (st_mode) or None if the file path does not exist.

Return type

byte

cryptopyutils.files.key(host_dns, out_dir=None)[source]

Generate the filepath for a private key

Parameters
  • host_dns (str) – The FDQN of the host.

  • out_dir (str, optional) – The directory. Defaults to None.

Returns

The filepath.

Return type

str

cryptopyutils.files.pem(host_dns, out_dir=None)[source]

Generate the filepath for a PEM private key file

Parameters
  • host_dns (str) – The FDQN of the host.

  • out_dir (str, optional) – The directory. Defaults to None.

Returns

The filepath.

Return type

str

cryptopyutils.files.pub(host_dns, out_dir=None)[source]

Generate the filepath for a SSH public key file

Parameters
  • host_dns (str) – The FDQN of the host.

  • out_dir (str, optional) – The directory. Defaults to None.

Returns

The filepath.

Return type

str

cryptopyutils.files.read(path, encoding=None, istext=False)[source]

Reads the data (binary of text) from the file

Parameters
  • path (str) – the file path

  • encoding (str, optional) – the encoding. Defaults to None.

  • istext (bool) – indicate if it should be written as text.

Returns

the content of the file.

Return type

str

cryptopyutils.files.set_chmod(path, mode)[source]

Set the chmod of a file

Parameters
  • path (str) – the file path.

  • mode (byte) – the file mode.

Returns

the file mode (st_mode) as read back or None if the file path

does not exist.

Return type

byte

cryptopyutils.files.write(path, data, encoding=None, istext=False)[source]

Write the data (binary or text) to the file

Parameters
  • path (str) – the file path.

  • data (bytes) – the content to write to the file.

  • encoding (str, optional) – the encoding. Defaults to None.

  • istext (bool) – indicates if it should be written as text.

Returns

True if performed successfully.

Return type

bool

cryptopyutils.password module

password.py - Password : derive, verify

Class:

  • Password

https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/

class cryptopyutils.password.Password(conf=<cryptopyutils.config.PasswordConfig object>)[source]

Bases: object

Password Management Object

derive(password)[source]

Generate a password using the PDKDF2 algorithm

Parameters

password (bytes or str) – the password. Bytes or string. If string, encoded in UTF-8.

Returns

The derived key. bytes: The salt.

Return type

bytes

gen_salt(length=16)[source]

Generate a salt

Parameters

length (int, optional) – Length of the salt. Defaults to 16.

Returns

salt

Return type

bytes

verify(attempt, key, salt)[source]

Verify a password using the PDKDF2 algorithm

Parameters
  • attempt (bytes or str) – the tentative password to be checked. If string, encoded in UTF-8.

  • key (bytes) – The key.

  • salt (bytes) – The salt.

Returns

True if verified, False if not verified

Return type

bool

cryptopyutils.privatekey module

privatekey.py - Private Key : generate, save, load, decrypt, sign

Class:

  • PrivateKey

class cryptopyutils.privatekey.PrivateKey(**kwargs)[source]

Bases: Base

PrivateKey class - extends Base

Usage (minimum requirements):

  • initialize : privk = PrivateKey() or privk = PrivateKey(PrivateKey())

  • generate key: privk.gen(alg)

  • save key: privk.save(filepath)

  • load key: privk.load(filepath)

  • decrypt: privk.decrypt(ciphertext)

  • sign: privk.sign(message)

decrypt(ciphertext, padding=None, text=False)[source]

Decrypt the encrypted message using the private key

The decrypted message can be represented in binary or text format. If text, it is decoded to UTF-8.

Parameters
  • ciphertext (base64) – The ciphertext to decrypt in base 64.

  • padding (AsymmetricPadding, optional) – An instance of AsymmetricPadding. Defaults to None.

  • text (bool, optional) – Flag indicating if the output should be treated

  • text. (as) – Defaults to False.

Returns

The plaintext.

Return type

bytes or str

gen(alg=None, key_size=None, public_exponent=None, curve=None)[source]

Generate the private key

Parameters
  • alg (str) – The key algorithm. RSA, EC, ED448, ED25519 and DSA are supported. Defaults to None.

  • key_size (int, optional) – Key size. Used in DSA and RSA. Defaults to None.

  • public_exponent (int, optional) – Public Exponent. Used in RSA. Defaults to None.

  • curve (str) – The name of the elliptic curve. Defaults to None.

gen_dsa(key_size=None)[source]

Generate a DSA private key

Parameters

key_size (int, optional) – Key size. Defaults to None.

gen_ec(curve=None)[source]

Generate an Elliptic Curve private key

Parameters

curve (str) – The name of the elliptic curve. Defaults to None.

gen_ed25519()[source]

Generate an ED25519 private key

gen_ed448()[source]

Generate an ED448 private key

gen_rsa(key_size=None, public_exponent=None)[source]

Generate a RSA private key

Parameters
  • key_size (int, optional) – Key size. Defaults to None.

  • public_exponent (int, optional) – Public Exponent. Defaults to None.

property key

Get the key attribute

Returns

An instance of an alg PrivateKey from Cryptography

(e.g. RSAPrivateKey).

Return type

Cryptography Private Key

property keytext

Returns the key in PEM PKCS8 format

Returns

the key.

Return type

str

load(path, encoding=None, passphrase=None)[source]

Load the private key

Parameters
  • path (str) – The file path of the key to be loaded. Defaults to None.

  • encoding (str, optional) – Encoding PEM, DER or OpenSSH. Defaults to None.

  • passphrase (str, optional) – The passphrase. Only for encrypted PEM or openSSH files. Default to None.

load_der(path, passphrase=None)[source]

Load a DER Private Key

Parameters
  • path (str) – The file path of the private key to be loaded.

  • passphrase (str, optional) – The passphrase.

load_pem(path, passphrase=None)[source]

Load a PEM Private Key

Parameters
  • path (str) – The file path of the private key to be loaded.

  • passphrase (str, optional) – The passphrase. Defaults to None.

save(path, encoding=None, file_format=None, passphrase=None, file_mode=None, force=False)[source]

Save the private key

Parameters
  • path (str) – The file path where the private key will be saved.

  • encoding (str, optional) – Encoding PEM, DER or OpenSSH.

  • None. (Defaults to) –

  • file_format (str, optional) – Format : PKCS8, PKCS or OpenSSH.

  • None.

  • passphrase (str, optional) – The passphrase.

  • None.

  • file_mode (byte, optional) – The file mode (chmod).

  • None.

  • force (bool, optional) – Force to replace file if already exists.

  • False. (Defaults to) –

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

save_der(path, file_format=None, passphrase=None, file_mode=None, force=False)[source]

Save a DER private key

Parameters
  • path (str) – The file path where the private key will be saved.

  • file_format (str, optional) – Format : PKCS8, PKCS1 or OpenSSH. Defaults to None.

  • passphrase (str, optional) – The passphrase. Defaults to None.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

save_pem(path, file_format=None, passphrase=None, file_mode=None, force=False)[source]

Save a PEM private key

Parameters
  • path (str) – The file path where the private key will be saved.

  • file_format (str, optional) – Format : PKCS8, PKCS1 or OpenSSH. Defaults to None.

  • passphrase (str, optional) – The passphrase. Defaults to None.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

sign(message, hash_alg=None, padding=None, pre_hashed=False)[source]

Sign the message using the private key

The message to sign is represented in binary or text format. If text, it is encoded in UTF-8.

Supports RSA, DSA, ED448, ED25519, Elliptic Curve (with ECDSA) Private Keys.

Parameters
  • message (bytes or str) – The message to sign.

  • hash_alg (str) – Defaults to None.

  • padding (AsymmetricPadding, optional) – An instance of AsymmetricPadding. Not in DSA. Defaults to None.

  • pre_hashed (bool, optional) – Flag indicating the the message is a digest from pre-hashed values (message too large). Defaults to False

Returns

The signature in base64 format.

Return type

str

cryptopyutils.publickey module

publickey.py - Public Key : generate, save, load, encrypt, verify

Class:

  • PublicKey

class cryptopyutils.publickey.PublicKey(**kwargs)[source]

Bases: Base

Public Key Class - extends Base

Usage:

  • initializepubk = PublicKey(PublicKey()) or pk = PublicKey()

    or pubk = PublicKey(private_key=PrivateKey())

  • generate the key: pubk.gen()

  • save key: pubk.save(filepath)

  • load key: pubk.load(filepath)

  • decrypt: pubk.decrypt(ciphertext)

  • verify: pubk.verify(signature, message)

encrypt(plaintext, padding=None)[source]

Encrypt the message using the public key

The plaintext can be binary or text format. If text, it is encoded in UTF-8.

Parameters
  • plaintext (bytes or str) – The plaintext to encrypt.

  • padding (AsymmetricPadding, optional) – An instance of AsymmetricPadding. Defaults to None.

Returns

The encrypted message in base 64 format.

Return type

base64

gen(alg=None, private_key=None)[source]

Generate the Public Key

Parameters
  • alg (str) – The key algorithm. RSA, EC, ED448, ED25519 and DSA are supported. Defaults to None.

  • private_key (PrivateKey, optional) – The private key. An instance of PrivateKey. Defaults to None.

property key

Get the key attribute

Returns

An instance of PublicKey from Cryptography.

Return type

Cryptography Public Key

property keytext

Returns the key in PEM SubjectPublicKeyInfo format

Returns

the key.

Return type

str

load(path, encoding=None)[source]

Load the public key

Parameters
  • path (str) – The file path of the public key to be loaded.

  • encoding (str, optional) – Encoding PEM, DER, openSSH, X962, SMIME. Defaults to None.

load_der(path)[source]

Load a DER Public Key

Parameters

path (str) – The file path of the public key to be loaded.

load_pem(path)[source]

Load a PEM Public Key

Parameters

path (str) – The file path of the public key to be loaded.

property private_key

Get the private_key attribute

Returns

An instance of PrivateKey.

Return type

PrivateKey

save(path, encoding=None, file_format=None, file_mode=None, force=False)[source]

Save the public key to file

Notes:

  • SSH format requires PEM encoding.

  • Default SubjectPublicKeyInfo format (None) requires PEM or DER encoding

  • PKCS8 is the default (Traditional openSSL style is kept as legacy)

Parameters
  • path (str) – The file path where the public key will be saved.

  • encoding (str, optional) – Encoding PEM, DER or OpenSSH. Defaults to None.

  • file_format (str, optional) – Format : SubjectPublicKeyInfo, PKCS1 or OpenSSH. Defaults to None.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

save_der(path, file_format=None, file_mode=None, force=False)[source]

Save a DER private key

Parameters
  • path (str) – The file path where the private key will be saved.

  • file_format (str, optional) – Format : SubjectPublicKeyInfo, PKCS1 or OpenSSH. Defaults to None.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

save_pem(path, file_format=None, file_mode=None, force=False)[source]

Save a PEM private key

Parameters
  • path (str) – The file path where the private key will be saved.

  • file_format (str, optional) – Format : SubjectPublicKeyInfo, PKCS1 or OpenSSH. Defaults to None.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

verify(signature, message, hash_alg=None, padding=None, pre_hashed=False)[source]

Sign the message using the public key

The message to verify can be binary or text format. If text, it is encoded in UTF-8.

Supports RSA, DSA, ED448, ED25519, Elliptic Curve (with ECDSA) Private Keys.

Parameters
  • signature (base64) – The signature in base64 format.

  • message (bytes or str) – The message to verify.

  • hash_alg (str, optional) – Defaults to None.

  • padding (AsymmetricPadding, optional) – An instance of AsymmetricPadding. Not in DSA. Defaults to None.

  • pre_hashed (bool, optional) – Flag indicating the the message is a digest from pre-hashed values (message too large). Defaults to False.

Raises

bool – False if the signature does not validate, else True.

cryptopyutils.sshkeypair module

sshkeypair.py - generate, save and load keypairs for OpenSSH

Class: - SSH

class cryptopyutils.sshkeypair.SSHKeyPair(**kwargs)[source]

Bases: Base

SSH Object - extends Base

gen_private_key(alg='RSA', key_size=None, public_exponent=None, curve=None)[source]

Generate a private key for OpenSSH

Parameters
  • alg (str, optional) – The key algorithm. RSA, ED25519, ECDSA and DSA (legacy) are supported. Defaults to RSA.

  • key_size (int, optional) – Key size. Used in RSA. Defaults to None.

  • public_exponent (int, optional) – Public Exponent. Used in RSA. Defaults to None.

  • curve (str, optional) – The name of the elliptic curve for ECDSA. Defaults to None.

  • passphrase (str, optional) – The passphrase. Defaults to None.

gen_public_key()[source]

Generate the SSH public key

Assumes you have generated the private key first.

hash_fingerprint(path, hash_alg=None)[source]

Get the fingerprint based on a hash function

equivalent to ssh-keygen -l -f /id_rsa.pub | awk ‘(print $2)’

Parameters
  • path (str) – path to the public key file

  • hash_alg (str, optional) – The hash algorithm. Defaults to None.

key_pair(alg='RSA', out_dir=None, passphrase=None, file_mode=None, force=False, key_size=None, public_exponent=None, curve_length=521, comment=None, is_user=True)[source]

Generate the SSH key pair using RSA

Parameters
  • alg (str, optional) – The key algorithm. RSA, ED25519, ECDSA and DSA (legacy) are supported. Defaults to RSA.

  • out_dir (str, optional) – The output directory path. Defaults to None.

  • passphrase (str, optional) – The passphrase. Defaults to None.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

  • key_size (int, optional) – Key size. Used in RSA. Defaults to None.

  • public_exponent (int, optional) – Public Exponent. Used in RSA. Defaults to None.

  • curve (int) – The elliptic curve length for ECDSA. Can be 256, 384 or 521. Defaults to 521.

  • comment (str, optional) – comment. Typically user@host format to be appended at the end of the public key. Defaults to None.

  • is_user (bool, optional) – Is the key a user key (True) or a system key (False). Defaults to True.

Returns

The first is the private key, the second is the public key.

bool: True if successful. False if already exists and not forced to overwrite. str: Private key and public key file pathes

Return type

[bool, bool], [str, str]

load_private_key(path, passphrase=None)[source]

Load a SSH Private Key

Parameters
  • filepath (str) – The file path of the private key to be loaded.

  • passphrase (str, optional) – The passphrase. Default to None.

load_public_key(path)[source]

Load a SSH Public Key

Parameters

path (str) – The file path of the public key to be loaded.

property private_key

Get the private_key attribute

Returns

An instance of PrivateKey.

Return type

PrivateKey

property public_key

Get the public_key attribute

Returns

An instance of PublicKey.

Return type

PublicKey

save_private_key(path, passphrase=None, file_mode=None, force=False)[source]

Save the SSH private key

Parameters
  • path (str) – The file path where the private key will be saved.

  • passphrase (str, optional) – The passphrase. Defaults to None.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

save_public_key(path, file_mode=None, force=False, comment=None)[source]

Save the SSH public key

Will open the file after saving it to apprend the comment if provided.

Parameters
  • path (str) – The file path where the public key will be saved.

  • file_mode (byte, optional) – The file mode (chmod). Defaults to None.

  • force (bool, optional) – Force to replace file if already exists. Defaults to False.

  • comment (str, optional) – comment. Typically user@host format to be appended at the end of the public key. Defaults to None.

Returns

True if successful. False if already exists and not forced

to overwrite.

Return type

bool

cryptopyutils.utils module

utils.py - Utils

cryptopyutils.utils.compare_bytes(left, right)[source]

Compares two series of bytes

Uses constant times to prevent timing attacks.

Parameters
  • left (bytes) – left series of bytes.

  • right (bytes) – right series of bytes.

Returns

True if equal, False if not equal.

Return type

bool

cryptopyutils.utils.convert_passphrase(passphrase)[source]

Converts the passphrase if needed

Parameters

passphrase (str) – Key password / passphrase string.

Returns

None or bytes.

cryptopyutils.utils.ellipctic_curve(name=None)[source]

Returns the Elliptic Curve object based on its name

Parameters
  • name (str, optional) – The name of the elliptic curve.

  • None. (Defaults to) –

Returns

An instance of the Elliptic Curve.

Return type

EllipticCurve

cryptopyutils.utils.file_encoding(encoding=None)[source]

Returns the file encoding

Parameters

encoding (str, optional) – Encoding PEM, DER or OpenSSH Not supported by cryptopyutils: RAW, X962, SMIME. Defaults to None. https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/

Returns

A serialization Encoding object.

Return type

Encoding

cryptopyutils.utils.hash_algorithm(alg=None)[source]

Returns the HashAlgorithm object for a given algorithm

https://cryptography.io/en/latest/hazmat/primitives/cryptographic-hashes

Parameters

alg (str) – The hashing algorithm. Defaults to None.

Returns

An instance of HashAlgorithm.

Return type

HashAlgorithm

cryptopyutils.utils.oaep_mgf1_padding(hash_alg=None)[source]

RSA OAEP MGF1 Padding

Parameters

hash_alg (str, optional) – the name of the hash algorithm. Defaults to None.

cryptopyutils.utils.private_alg(passphrase)[source]

Private algorithm

Parameters

passphrase (str) – Key password / passphrase string.

cryptopyutils.utils.private_format(fmt=None)[source]

Returns the private key format

Parameters

fmt (str, optional) – Format : PKCS8, PKCS1 or OpenSSH. Not supported by cryptopyutils: RAW Defaults to None. https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/

Returns

A serialization PrivateFormat object.

Return type

PrivateFormat

cryptopyutils.utils.pss_mgf1_padding(hash_alg=None)[source]

Signature PSS MGF1 Padding

Parameters

hash_alg (str, optional) – the name of the hash algorithm. Defaults to None.

cryptopyutils.utils.public_format(fmt=None)[source]

Returns the public key format

Parameters

fmt (str, optional) – Format : SubjectPublicKeyInfo, PKCS1 or OpenSSH. Not supported by cryptopyutils: RAW, CompressedPoint, UncompressedPoint Defaults to None.

Returns

A serialization PublicFormat object.

Return type

PublicFormat

Module contents