# M2Crypto Package

## `M2Crypto` Package

M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, DH, EC, HMACs, message digests, symmetric ciphers (including AES); SSL functionality to implement clients and servers; HTTPS extensions to Python’s httplib, urllib, and xmlrpclib; unforgeable HMAC’ing AuthCookies for web session management; FTP/TLS client and server; and ZSmime: An S/MIME messenger for Zope. M2Crypto can also be used to provide SSL for Twisted.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

Portions created by Open Source Applications Foundation (OSAF) are Copyright (C) 2004-2007 OSAF. All Rights Reserved.

Copyright 2008-2011 Heikki Toivonen. All rights reserved.

## `ASN1` Module

M2Crypto wrapper for OpenSSL ASN1 API.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

Portions created by Open Source Applications Foundation (OSAF) are Copyright (C) 2005 OSAF. All Rights Reserved.

class M2Crypto.ASN1.ASN1_Integer(asn1int: ASN1_Integer | int, _pyfree: int = 0)

  Bases: `object`

class M2Crypto.ASN1.ASN1_Object(asn1obj: ASN1_Object, _pyfree: int = 0)

  Bases: `object`

  m2_asn1_object_free(object, /)

class M2Crypto.ASN1.ASN1_String(asn1str: ASN1_String | str | bytes, _pyfree: int = 0)

  Bases: `object`

  as_text(flags: int = 0) → str

    Output an ASN1_STRING structure according to the set flags.

    Parameters:

      flags – determine the format of the output by using predetermined constants, see ASN1_STRING_print_ex(3) manpage for their meaning.

    Returns:

      output an ASN1_STRING structure.

class M2Crypto.ASN1.ASN1_TIME(asn1_time: ASN1_Time | None = None, _pyfree: int = 0, asn1_utctime: ASN1_Time | None = None)

  Bases: `object`

  get_datetime() → datetime

    Get time as datetime.datetime object

    Returns:

      always return datetime object

    Raises:

      ValueError if anything wrong happens

  m2_asn1_time_free(object, /)
  set_datetime(date: datetime) → ASN1_Time

    Set time from datetime.datetime object.

    Returns:

      pointer to a time structure or NULL if an error occurred

  set_string(string: str) → int

    Set time from UTC string.

    Returns:

      1 if the time value is successfully set and 0 otherwise

  set_time(time: int) → ASN1_Time

    Set time from seconds since epoch (int).

    Returns:

      pointer to a time structure or NULL if an error occurred

M2Crypto.ASN1.ASN1_UTCTIME

  alias of `ASN1_TIME`

class M2Crypto.ASN1.LocalTimezone

  Bases: `tzinfo`

  Localtimezone from datetime manual.

  dst(dt: datetime | None) → timedelta

    datetime -> DST offset as timedelta positive east of UTC.

  tzname(dt: datetime | None) → str

    datetime -> string name of time zone.

  utcoffset(dt: datetime | None) → timedelta

    datetime -> timedelta showing offset from UTC, negative values indicating West of UTC

## `AuthCookie` Module

Secure Authenticator Cookies

Copyright (c) 1999-2002 Ng Pheng Siong. All rights reserved.

class M2Crypto.AuthCookie.AuthCookie(expiry: float, data: str, dough: str, mac: str)

  Bases: `object`

  data() → str

    Return the data portion of the cookie.

  expiry() → float

    Return the cookie’s expiry time.

  headerValue() → str
  isExpired() → bool

    Return 1 if the cookie has expired, 0 otherwise.

  mac() → str

    Return the cookie’s MAC.

  name() → str
  output(header: str = 'Set-Cookie:') → str

    Return the cookie’s output in “Set-Cookie” format.

  value() → str

    Return the cookie’s output minus the “Set-Cookie: “ portion.

class M2Crypto.AuthCookie.AuthCookieJar

  Bases: `object`

  isGoodCookie(cookie: AuthCookie) → bool
  isGoodCookieString(cookie_str: dict | str, _debug: bool = False) → bool
  makeCookie(expiry: float, data: str) → AuthCookie

    Make a cookie

    Parameters:

      - expiry – expiration time (float in seconds)

      - data – cookie content

    Returns:

      AuthCookie object

M2Crypto.AuthCookie.mix(expiry: float, data: str, format: str = 'exp=%f&data=%s&digest=') → str

M2Crypto.AuthCookie.unmix(dough: str | bytes, regex: Pattern = re.compile('exp=(\\d+\\.\\d+)&data=(.+)&digest=(\\S*)')) → Tuple[float, str] | None

M2Crypto.AuthCookie.unmix3(dough: str | bytes, regex: Pattern = re.compile('exp=(\\d+\\.\\d+)&data=(.+)&digest=(\\S*)')) → Tuple[float, str, str] | None

## `BIO` Module

M2Crypto wrapper for OpenSSL BIO API.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

class M2Crypto.BIO.BIO(bio: BIO | None = None, _pyfree: int = 0, _close_cb: Callable | None = None)

  Bases: `object`

  Abstract object interface to the BIO API.

  bio_ptr()
  close() → None
  fileno() → int
  flush() → None

    Flush the buffers.

    Returns:

      1 for success, and 0 or -1 for failure

  read(size: int | None = None) → bytes | bytearray
  readable() → bool
  readline(size: int = 4096) → bytes
  readlines(sizehint: str | bytes | int = 'ignored') → Iterable[bytes]
  reset() → int

    Set the bio to its initial state.

    Returns:

      1 for success, and 0 or -1 for failure

  seek(off)

    Seek to the specified absolute offset.

  should_read() → int

    Should we read more data?

  should_retry() → int

    Can the call be attempted again, or was there an error ie do_handshake

  should_write() → int

    Should we write more data?

  tell()

    Return the current offset.

  write(data: str | bytes) → int

    Write data to BIO.

    Returns:

      either data written, or [0, -1] for nothing written, -2 not implemented

  write_close() → None
  writeable() → bool

exception M2Crypto.BIO.BIOError

  Bases: `ValueError`

class M2Crypto.BIO.CipherStream(obio: BIO)

  Bases: `BIO`

  Object interface to BIO_f_cipher.

  SALT_LEN = 8
  close() → None
  set_cipher(algo: str, key: str | bytes, iv: str | bytes, op: int) → None
  write_close() → None

class M2Crypto.BIO.File(pyfile_arg: IO | str, close_pyfile: int = 1, mode: str = 'rb')

  Bases: `BIO`

  Object interface to BIO_s_pyfd.

  This class interfaces Python to OpenSSL functions that expect BIO. For general file manipulation in Python, use Python’s builtin file object.

  close() → None
  flush() → None

    Flush the buffers.

    Returns:

      1 for success, and 0 or -1 for failure

  reset() → int

    Set the bio to its initial state.

    Returns:

      0 for success, and -1 for failure

class M2Crypto.BIO.IOBuffer(under_bio: BIO, mode: str = 'rwb', _pyfree: int = 1)

  Bases: `BIO`

  Object interface to BIO_f_buffer.

  Its principal function is to be BIO_push()’ed on top of a BIO_f_ssl, so that makefile() of said underlying SSL socket works.

  close() → None

class M2Crypto.BIO.MemoryBuffer(data: bytes | None = None)

  Bases: `BIO`

  Object interface to BIO_s_mem.

  Empirical testing suggests that this class performs less well than cStringIO, because cStringIO is implemented in C, whereas this class is implemented in Python. Thus, the recommended practice is to use cStringIO for regular work and convert said cStringIO object to a MemoryBuffer object only when necessary.

  close() → None
  getvalue(size: int | None = None) → bytes
  read(size: int | None = None) → bytes
  read_all(size: int | None = None) → bytes
  write_close() → None

class M2Crypto.BIO.SSLBio(_pyfree: int = 1)

  Bases: `BIO`

  Object interface to BIO_f_ssl.

  do_handshake() → int

    Do the handshake.

    Return 1 if the handshake completes Return 0 or a negative number if there is a problem

  set_ssl(conn: SSL.Connection, close_flag: int = 0) → None

    Sets the bio to the SSL pointer which is contained in the connection object.

M2Crypto.BIO.openfile(filename: str | bytes, mode: str = 'rb') → File

## `BN` Module

M2Crypto wrapper for OpenSSL BN (BIGNUM) API.

Copyright (c) 2005 Open Source Applications Foundation. All rights reserved.

M2Crypto.BN.rand(bits: int, top: int = -1, bottom: int = 0) → int | None

  Generate cryptographically strong random number.

  Parameters:

    - bits – Length of random number in bits.

    - top – If -1, the most significant bit can be 0. If 0, the most significant bit is 1, and if 1, the two most significant bits will be 1.

    - bottom – If bottom is true, the number will be odd.

M2Crypto.BN.rand_range(range: int) → int

  Generate a random number in a range.

  Parameters:

    range – Upper limit for range.

  Returns:

    A random number in the range [0, range)

M2Crypto.BN.randfname(length: int) → str

  Return a random filename, which is simply a string where all the characters are from the set [a-zA-Z0-9].

  Parameters:

    length – Length of filename to return.

  Returns:

    random filename string

## `DH` Module

M2Crypto wrapper for OpenSSL DH API.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

class M2Crypto.DH.DH(dh: DH, _pyfree: int = 0)

  Bases: `object`

  Object interface to the Diffie-Hellman key exchange protocol.

  check_params() → int
  compute_key(pubkey: bytes) → bytes
  gen_key() → None
  static m2_dh_free(dh: DH) → None
  print_params(bio: BIO) → int

exception M2Crypto.DH.DHError

  Bases: `Exception`

M2Crypto.DH.gen_params(plen: int, g: int, callback: ~typing.Callable = <function genparam_callback>) → DH

M2Crypto.DH.load_params(file: str | bytes) → DH

M2Crypto.DH.load_params_bio(bio: BIO) → DH

M2Crypto.DH.set_params(p: bytes, g: bytes) → DH

## `DSA` Module

M2Crypto wrapper for OpenSSL DSA API.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

Portions created by Open Source Applications Foundation (OSAF) are Copyright (C) 2004 OSAF. All Rights Reserved.

class M2Crypto.DSA.DSA(dsa: DSA, _pyfree: int = 0)

  Bases: `object`

  This class is a context supporting DSA key and parameter values, signing and verifying.

  Simple example:

      from M2Crypto import EVP, DSA, util

      message = 'Kilroy was here!'
      md = EVP.MessageDigest('sha256')
      md.update(message)
      digest = md.final()

      dsa = DSA.gen_params(1024, cb)
      dsa.gen_key()
      r, s = dsa.sign(digest)
      good = dsa.verify(digest, r, s)
      if good:
          print('  ** success **')
      else:
          print('  ** verification failed **')

  check_key()

    Check to be sure the DSA object has a valid private key.

    Returns:

      1 (true) if a valid private key

  gen_key() → None

    Generate a key pair.

  static m2_dsa_free(dsa: DSA) → None
  save_key(filename: str | bytes, cipher: str = 'aes_128_cbc', callback: ~typing.Callable = <function passphrase_callback>) → int

    Save the DSA key pair to a file.

    Parameters:

      - filename – Save the DSA key pair to this file.

      - cipher – name of symmetric key algorithm and mode to encrypt the private key.

    Returns:

      1 (true) if successful

  save_key_bio(bio: ~M2Crypto.BIO.BIO, cipher: str = 'aes_128_cbc', callback: ~typing.Callable = <function passphrase_callback>) → int

    Save DSA key pair to a BIO object.

    Parameters:

      - bio – Save DSA parameters to this object.

      - cipher – name of symmetric key algorithm and mode to encrypt the private key.

    Returns:

      1 (true) if successful

  save_params(filename: str | bytes) → int

    Save the DSA parameters to a file.

    Parameters:

      filename – Save the DSA parameters to this file.

    Returns:

      1 (true) if successful

  save_params_bio(bio: BIO) → int

    Save DSA parameters to a BIO object.

    Parameters:

      bio – Save DSA parameters to this object.

    Returns:

      1 (true) if successful

  save_pub_key(filename: str | bytes) → int

    Save the DSA public key (with parameters) to a file.

    Parameters:

      filename – Save DSA public key (with parameters) to this file.

    Returns:

      1 (true) if successful

  save_pub_key_bio(bio: BIO) → int

    Save DSA public key (with parameters) to a BIO object.

    Parameters:

      bio – Save DSA public key (with parameters) to this object.

    Returns:

      1 (true) if successful

  set_params(p: bytes, q: bytes, g: bytes) → None

    Set new parameters.

    Parameters:

      - p – MPI binary representation … format that consists of the number’s length in bytes represented as a 4-byte big-endian number, and the number itself in big-endian format, where the most significant bit signals a negative number (the representation of numbers with the MSB set is prefixed with null byte).

      - q – ditto

      - g – ditto

    @warning: This does not change the private key, so it may be

      unsafe to use this method. It is better to use gen_params function to create a new DSA object.

  sign(digest: bytes) → Tuple[bytes, bytes]

    Sign the digest.

    Parameters:

      digest – SHA-1 hash of message (same as output from MessageDigest, a “byte string”)

    Returns:

      DSA signature, a tuple of two values, r and s, both “byte strings”.

  sign_asn1(digest)
  verify(digest: bytes, r: bytes, s: bytes) → int

    Verify a newly calculated digest against the signature values r and s.

    Parameters:

      - digest – SHA-1 hash of message (same as output from MessageDigest, a “byte string”)

      - r – r value of the signature, a “byte string”

      - s – s value of the signature, a “byte string”

    Returns:

      1 (true) if verify succeeded, 0 if failed

  verify_asn1(digest, blob)

exception M2Crypto.DSA.DSAError

  Bases: `Exception`

class M2Crypto.DSA.DSA_pub(dsa: DSA, _pyfree: int = 0)

  Bases: `DSA`

  This class is a DSA context that only supports a public key and verification. It does NOT support a private key or signing.

  check_key() → int
    Returns:

      does DSA_pub contain a pub key?

  save_key(filename: str | bytes) → int

    Save the DSA public key (with parameters) to a file.

    Parameters:

      filename – Save DSA public key (with parameters) to this file.

    Returns:

      1 (true) if successful

  save_key_bio(bio: BIO) → int

    Save DSA public key (with parameters) to a BIO object.

    Parameters:

      bio – Save DSA public key (with parameters) to this object.

    Returns:

      1 (true) if successful

  sign(digest: bytes = b'') → NoReturn

    Sign the digest.

    Parameters:

      digest – SHA-1 hash of message (same as output from MessageDigest, a “byte string”)

    Returns:

      DSA signature, a tuple of two values, r and s, both “byte strings”.

  sign_asn1(digest: bytes = b'') → NoReturn

    Sign the digest.

    Parameters:

      digest – SHA-1 hash of message (same as output from MessageDigest, a “byte string”)

    Returns:

      DSA signature, a tuple of two values, r and s, both “byte strings”.

M2Crypto.DSA.gen_params(bits: int, callback: ~typing.Callable[[int, int], int] = <function genparam_callback>) → DSA

  Factory function that generates DSA parameters and instantiates a DSA object from the output.

  Parameters:

    - bits – The length of the prime to be generated. If ‘bits’ < 512, it is set to 512.

    - callback – A Python callback object that will be invoked during parameter generation; it usual purpose is to provide visual feedback.

  Returns:

    instance of DSA.

M2Crypto.DSA.load_key(file: str | bytes, callback: ~typing.Callable = <function passphrase_callback>) → DSA

  Factory function that instantiates a DSA object from a PEM encoded DSA key pair.

  Parameters:

    - file – Names the file (a path) that contains the PEM representation of the DSA key pair.

    - callback – A Python callback object that will be invoked if the DSA key pair is passphrase-protected.

  Returns:

    instance of DSA.

M2Crypto.DSA.load_key_bio(bio: ~M2Crypto.BIO.BIO, callback: ~typing.Callable = <function passphrase_callback>) → DSA

  Factory function that instantiates a DSA object from a PEM encoded DSA key pair.

  Parameters:

    - bio – Contains the PEM representation of the DSA key pair.

    - callback – A Python callback object that will be invoked if the DSA key pair is passphrase-protected.

  Returns:

    instance of DSA.

M2Crypto.DSA.load_params(file: str | bytes, callback: ~typing.Callable = <function passphrase_callback>) → DSA

  Factory function that instantiates a DSA object with DSA parameters from a file.

  Parameters:

    - file – Names the file (a path) that contains the PEM representation of the DSA parameters.

    - callback – A Python callback object that will be invoked if the DSA parameters file is passphrase-protected.

  Returns:

    instance of DSA.

M2Crypto.DSA.load_params_bio(bio: ~M2Crypto.BIO.BIO, callback: ~typing.Callable = <function passphrase_callback>) → DSA

  Factory function that instantiates a DSA object with DSA parameters from a M2Crypto.BIO object.

  Parameters:

    - bio – Contains the PEM representation of the DSA parameters.

    - callback – A Python callback object that will be invoked if the DSA parameters file is passphrase-protected.

  Returns:

    instance of DSA.

M2Crypto.DSA.load_pub_key(file: str | bytes, callback: ~typing.Callable = <function passphrase_callback>) → DSA_pub

  Factory function that instantiates a DSA_pub object using a DSA public key contained in PEM file. The PEM file must contain the parameters in addition to the public key.

  Parameters:

    - file – Names the file (a path) that contains the PEM representation of the DSA public key.

    - callback – A Python callback object that will be invoked should the DSA public key be passphrase-protected.

  Returns:

    instance of DSA_pub.

M2Crypto.DSA.load_pub_key_bio(bio: ~M2Crypto.BIO.BIO, callback: ~typing.Callable = <function passphrase_callback>) → DSA_pub

  Factory function that instantiates a DSA_pub object using a DSA public key contained in PEM format. The PEM must contain the parameters in addition to the public key.

  Parameters:

    - bio – Contains the PEM representation of the DSA public key (with params).

    - callback – A Python callback object that will be invoked should the DSA public key be passphrase-protected.

  Returns:

    instance of DSA_pub.

M2Crypto.DSA.pub_key_from_params(p: bytes, q: bytes, g: bytes, pub: bytes) → DSA_pub

  Factory function that instantiates a DSA_pub object using the parameters and public key specified.

  Parameters:

    - p – value of p

    - q – value of q

    - g – value of g

    - pub – value of the public key

  Returns:

    instance of DSA_pub.

M2Crypto.DSA.set_params(p: bytes, q: bytes, g: bytes) → DSA

  Factory function that instantiates a DSA object with DSA parameters.

  Parameters:

    - p – value of p, a “byte string”

    - q – value of q, a “byte string”

    - g – value of g, a “byte string”

  Returns:

    instance of DSA.

## `EC` Module

M2Crypto wrapper for OpenSSL ECDH/ECDSA API.

@requires: OpenSSL 0.9.8 or newer

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

Portions copyright (c) 2005-2006 Vrije Universiteit Amsterdam. All rights reserved.

class M2Crypto.EC.EC(ec: EC_KEY, _pyfree: int = 0)

  Bases: `object`

  Object interface to a EC key pair.

  as_pem(cipher: str = 'aes_128_cbc', callback: ~typing.Callable = <function passphrase_callback>) → bytes

    Returns the key(pair) as a string in PEM format. If no password is passed and the cipher is set it exits with error

  check_key() → int
  compute_dh_key(pub_key: EC) → bytes | None

    Compute the ECDH shared key of this key pair and the given public key object. They must both use the same curve. Returns the shared key in binary as a buffer object. No Key Derivation Function is applied.

  gen_key() → None

    Generates the key pair from its parameters. Use:

        keypair = EC.gen_params(curve)
        keypair.gen_key()

    to create an EC key pair.

  static m2_ec_key_free(ec: EC_KEY) → None
  pub() → EC_pub
  save_key(file: str | bytes, cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable = <function passphrase_callback>) → int

    Save the key pair to a file in PEM format.

    Parameters:

      - file – Name of filename to save key to.

      - cipher – Symmetric cipher to protect the key. The default cipher is ‘aes_128_cbc’. If cipher is None, then the key is saved in the clear.

      - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key. The default is util.passphrase_callback.

  save_key_bio(bio: ~M2Crypto.BIO.BIO, cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable = <function passphrase_callback>) → int

    Save the key pair to an M2Crypto.BIO.BIO object in PEM format.

    Parameters:

      - bio – M2Crypto.BIO.BIO object to save key to.

      - cipher – Symmetric cipher to protect the key. The default cipher is ‘aes_128_cbc’. If cipher is None, then the key is saved in the clear.

      - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key. The default is util.passphrase_callback.

  save_pub_key(file: str | bytes) → int

    Save the public key to a filename in PEM format.

    Parameters:

      file – Name of filename to save key to.

  save_pub_key_bio(bio: BIO) → int

    Save the public key to an M2Crypto.BIO.BIO object in PEM format.

    Parameters:

      bio – M2Crypto.BIO.BIO object to save key to.

  sign_dsa(digest: bytes) → Tuple[bytes, bytes]

    Sign the given digest using ECDSA. Returns a tuple (r,s), the two ECDSA signature parameters.

  sign_dsa_asn1(digest: bytes) → bytes
  verify_dsa(digest: bytes, r: bytes, s: bytes) → int

    Verify the given digest using ECDSA. r and s are the ECDSA signature parameters.

  verify_dsa_asn1(digest: bytes, blob: bytes) → int

exception M2Crypto.EC.ECError

  Bases: `Exception`

class M2Crypto.EC.EC_pub(ec: EC_KEY, _pyfree: int = 0)

  Bases: `EC`

  Object interface to an EC public key. ((don’t like this implementation inheritance))

  as_pem()

    Returns the key(pair) as a string in PEM format. If no password is passed and the cipher is set it exits with error

  get_der() → bytes

    Returns the public key in DER format as a buffer object.

  get_key() → bytes

    Returns the public key as a byte string.

  save_key(file: str | bytes) → int

    Save the public key to a filename in PEM format.

    Parameters:

      file – Name of filename to save key to.

  save_key_bio(bio: BIO) → int

    Save the public key to an M2Crypto.BIO.BIO object in PEM format.

    Parameters:

      bio – M2Crypto.BIO.BIO object to save key to.

M2Crypto.EC.ec_error() → NoReturn

M2Crypto.EC.gen_params(curve: int) → EC

  Factory function that generates EC parameters and instantiates a EC object from the output.

  Parameters:

    curve – This is the OpenSSL nid of the curve to use.

M2Crypto.EC.get_builtin_curves() → List[Dict[str, int | str]]

M2Crypto.EC.load_key(file: str | bytes, callback: ~typing.Callable = <function passphrase_callback>) → EC

  Factory function that instantiates a EC object.

  Parameters:

    - file – Names the filename that contains the PEM representation of the EC key pair.

    - callback – Python callback object that will be invoked if the EC key pair is passphrase-protected.

M2Crypto.EC.load_key_bio(bio: ~M2Crypto.BIO.BIO, callback: ~typing.Callable = <function passphrase_callback>) → EC

  Factory function that instantiates a EC object.

  Parameters:

    - bio – M2Crypto.BIO object that contains the PEM representation of the EC key pair.

    - callback – Python callback object that will be invoked if the EC key pair is passphrase-protected.

M2Crypto.EC.load_key_string(string: str, callback: ~typing.Callable = <function passphrase_callback>) → EC

  Load an EC key pair from a string.

  Parameters:

    - string – String containing EC key pair in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to unlock the key. The default is util.passphrase_callback.

  Returns:

    M2Crypto.EC.EC object.

M2Crypto.EC.load_key_string_pubkey(string: str, callback: ~typing.Callable = <function passphrase_callback>) → PKey

  Load an M2Crypto.EVP.PKey from a public key as a string.

  Parameters:

    - string – String containing the key in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key.

  Returns:

    M2Crypto.EVP.PKey object.

M2Crypto.EC.load_pub_key(file: str | bytes) → EC_pub

  Load an EC public key from filename.

  Parameters:

    file – Name of filename containing EC public key in PEM format.

  Returns:

    M2Crypto.EC.EC_pub object.

M2Crypto.EC.load_pub_key_bio(bio: BIO) → EC_pub

  Load an EC public key from an M2Crypto.BIO.BIO object.

  Parameters:

    bio – M2Crypto.BIO.BIO object containing EC public key in PEM format.

  Returns:

    M2Crypto.EC.EC_pub object.

M2Crypto.EC.pub_key_from_der(der: bytes) → EC_pub

  Create EC_pub from DER.

M2Crypto.EC.pub_key_from_params(curve: int, bytes: bytes) → EC_pub

  Create EC_pub from curve name and octet string.

## `EVP` Module

M2Crypto wrapper for OpenSSL EVP API.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

Portions Copyright (c) 2004-2007 Open Source Applications Foundation. Author: Heikki Toivonen

class M2Crypto.EVP.Cipher(alg: str, key: bytes, iv: bytes, op: int, key_as_bytes: int = 0, d: str = 'md5', salt: bytes = b'12345678', i: int = 1, padding: int = 1)

  Bases: `object`

  final() → bytes
  static m2_cipher_ctx_free(ctx: EVP_CIPHER_CTX) → None
  set_padding(padding: int = 1) → int

    Actually always return 1

  update(data: bytes) → bytes

exception M2Crypto.EVP.EVPError

  Bases: `ValueError`

class M2Crypto.EVP.HMAC(key: bytes, algo: str = 'sha256')

  Bases: `object`

  digest() → bytes
  final() → bytes
  static m2_hmac_ctx_free(ctx: HMAC_CTX) → None
  reset(key: bytes) → None
  update(data: bytes) → None

class M2Crypto.EVP.MessageDigest(algo: str)

  Bases: `object`

  Message Digest

  digest()
  final()
  static m2_md_ctx_free(ctx: EVP_MD_CTX) → None
  update(data: bytes) → int

    Add data to be digested.

    Returns:

      -1 for Python error, 1 for success, 0 for OpenSSL failure.

class M2Crypto.EVP.PKey(pkey: EVP_PKEY | None = None, _pyfree: int = 0, md: str = 'sha256')

  Bases: `object`

  Object to hold diverse types of asymmetric keys (also known as “key pairs”).

  as_der() → bytes

    Return key in DER format in a string

  as_pem(cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable = <function passphrase_callback>) → bytes

    Return key in PEM format in a string.

    Parameters:

      - cipher – Symmetric cipher to protect the key. The default cipher is `'aes_128_cbc'`. If cipher is None, then the key is saved in the clear.

      - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key. The default is util.passphrase_callback.

  assign_ec(ec: EC, capture: int = 1) → int

    Assign the EC key pair to self.

    Parameters:

      - ec – M2Crypto.EC.EC object to be assigned to self.

      - capture – If true (default), this PKey object will own the EC object, meaning that once the PKey object gets deleted it is no longer safe to use the EC object.

    Returns:

      Return 1 for success and 0 for failure.

  assign_rsa(rsa: RSA, capture: int = 1) → int

    Assign the RSA key pair to self.

    Parameters:

      - rsa – M2Crypto.RSA.RSA object to be assigned to self.

      - capture – If true (default), this PKey object will own the RSA object, meaning that once the PKey object gets deleted it is no longer safe to use the RSA object.

    Returns:

      Return 1 for success and 0 for failure.

  digest_sign(data: bytes) → bytes

    Return signature.

    Returns:

      The signature.

  digest_sign_final() → bytes

    Return signature.

    Returns:

      The signature.

  digest_sign_init() → None

    Initialise digest signing operation with self.

  digest_sign_update(data: bytes) → None

    Feed data to digest signing operation.

    Parameters:

      data – Data to be signed.

  digest_verify(sign: bytes, data: bytes) → int

    Return result of verification.

    Parameters:

      - sign – Signature to use for verification

      - data – Data to be verified.

    Returns:

      Result of verification: 1 for success, 0 for failure, -1 on other error.

  digest_verify_final(sign: bytes) → int

    Feed data to digest verification operation.

    Parameters:

      sign – Signature to use for verification

    Returns:

      Result of verification: 1 for success, 0 for failure, -1 on other error.

  digest_verify_init() → None

    Initialise verification operation with self.

  digest_verify_update(data: bytes) → int

    Feed data to verification operation.

    Parameters:

      data – Data to be verified.

    Returns:

      -1 on Python error, 1 for success, 0 for OpenSSL error

  final() → bytes

    Return signature.

    Returns:

      The signature.

  get_ec() → EC_pub

    Return the underlying EC key if that is what the EVP instance is holding.

  get_key_identifier() → bytes

    Return the Subject Key Identifier (SKID) calculated as the SHA-1 hash of the raw public key bytes (method 1 in RFC 5280, section 4.2.1.2).

    Returns:

      SHA1 digest (20 bytes) of the public key.

  get_modulus() → bytes | None

    Return the modulus in hex format.

  get_rsa() → RSA_pub

    Return the underlying RSA key if that is what the EVP instance is holding.

  reset_context(md: str = 'sha256') → None

    Reset internal message digest context.

    Parameters:

      md – The message digest algorithm.

  save_key(file: str | bytes, cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable = <function passphrase_callback>) → int

    Save the key pair to a file in PEM format.

    Parameters:

      - file – Name of file to save key to.

      - cipher – Symmetric cipher to protect the key. The default cipher is ‘aes_128_cbc’. If cipher is None, then the key is saved in the clear.

      - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key. The default is util.passphrase_callback.

  save_key_bio(bio: ~M2Crypto.BIO.BIO, cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable = <function passphrase_callback>) → int

    Save the key pair to the M2Crypto.BIO object ‘bio’ in PEM format.

    Parameters:

      - bio – M2Crypto.BIO object to save key to.

      - cipher – Symmetric cipher to protect the key. The default cipher is ‘aes_128_cbc’. If cipher is None, then the key is saved in the clear.

      - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key. The default is util.passphrase_callback.

  sign_final() → bytes

    Return signature.

    Returns:

      The signature.

  sign_init() → None

    Initialise signing operation with self.

  sign_update(data: bytes) → None

    Feed data to signing operation.

    Parameters:

      data – Data to be signed.

  size() → int

    Return the size of the key in bytes.

  update(data: bytes) → None

    Feed data to signing operation.

    Parameters:

      data – Data to be signed.

  verify_final(sign: bytes) → int

    Return result of verification.

    Parameters:

      sign – Signature to use for verification

    Returns:

      Result of verification: 1 for success, 0 for failure, -1 on other error.

  verify_init() → None

    Initialise signature verification operation with self.

  verify_update(data: bytes) → int

    Feed data to verification operation.

    Parameters:

      data – Data to be verified.

    Returns:

      -1 on Python error, 1 for success, 0 for OpenSSL error

M2Crypto.EVP.hmac(key: bytes, data: bytes, algo: str = 'sha256') → bytes

M2Crypto.EVP.load_key(file: str | bytes, callback: ~typing.Callable = <function passphrase_callback>) → PKey

  Load an M2Crypto.EVP.PKey from file.

  Parameters:

    - file – Name of file containing the key in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key.

  Returns:

    M2Crypto.EVP.PKey object.

M2Crypto.EVP.load_key_bio(bio: ~M2Crypto.BIO.BIO, callback: ~typing.Callable = <function passphrase_callback>) → PKey

  Load an M2Crypto.EVP.PKey from an M2Crypto.BIO object.

  Parameters:

    - bio – M2Crypto.BIO object containing the key in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key.

  Returns:

    M2Crypto.EVP.PKey object.

M2Crypto.EVP.load_key_bio_pubkey(bio: ~M2Crypto.BIO.BIO, callback: ~typing.Callable = <function passphrase_callback>) → PKey

  Load an M2Crypto.EVP.PKey from a public key as a M2Crypto.BIO object.

  Parameters:

    - bio – M2Crypto.BIO object containing the key in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key.

  Returns:

    M2Crypto.EVP.PKey object.

M2Crypto.EVP.load_key_pubkey(file: str | bytes, callback: ~typing.Callable = <function passphrase_callback>) → PKey

  Load an M2Crypto.EVP.PKey from a public key as a file.

  Parameters:

    - file – Name of file containing the key in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key.

  Returns:

    M2Crypto.EVP.PKey object.

M2Crypto.EVP.load_key_string(string: str | bytes, callback: ~typing.Callable = <function passphrase_callback>) → PKey

  Load an M2Crypto.EVP.PKey from a string.

  Parameters:

    - string – String containing the key in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key.

  Returns:

    M2Crypto.EVP.PKey object.

M2Crypto.EVP.load_key_string_pubkey(string: str | bytes, callback: ~typing.Callable = <function passphrase_callback>) → PKey

  Load an M2Crypto.EVP.PKey from a public key as a string.

  Parameters:

    - string – String containing the key in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key.

  Returns:

    M2Crypto.EVP.PKey object.

M2Crypto.EVP.pbkdf2(password: bytes, salt: bytes, iter: int, keylen: int) → bytes

  Derive a key from password using PBKDF2 algorithm specified in RFC 2898.

  Parameters:

    - password – Derive the key from this password.

    - salt – Salt.

    - iter – Number of iterations to perform.

    - keylen – Length of key to produce.

  Returns:

    Key.

## `Err` Module

M2Crypto wrapper for OpenSSL Error API.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

exception M2Crypto.Err.M2CryptoError

  Bases: `Exception`

exception M2Crypto.Err.SSLError(err: int, client_addr: Tuple[str, int] | str)

  Bases: `Exception`

M2Crypto.Err.get_error() → str | None

M2Crypto.Err.get_error_code() → int

M2Crypto.Err.get_error_func(err: int | None) → str

M2Crypto.Err.get_error_lib(err: int | None) → str

M2Crypto.Err.get_error_message() → str

M2Crypto.Err.get_error_reason(err: int | None) → str

M2Crypto.Err.get_x509_verify_error(err: int | None) → str

M2Crypto.Err.peek_error_code() → int

## `RC4` Module

M2Crypto wrapper for OpenSSL RC4 API.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

class M2Crypto.RC4.RC4(key: bytes | None = None)

  Bases: `object`

  Object interface to the stream cipher RC4.

  final() → str
  static rc4_free(cipher: RC4_KEY) → None
  set_key(key: bytes) → None
  update(data: bytes) → bytes

## `RSA` Module

M2Crypto wrapper for OpenSSL RSA API.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

class M2Crypto.RSA.RSA(rsa: RSA, _pyfree: int = 0)

  Bases: `object`

  RSA Key Pair.

  as_pem(cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable[[...], ~typing.Any] = <function passphrase_callback>) → bytes

    Returns the key(pair) as a string in PEM format.

  check_key() → int

    Validate RSA keys.

    It checks that p and q are in fact prime, and that n = p*q.

    Returns:

      returns 1 if rsa is a valid RSA key, and 0 otherwise. -1 is returned if an error occurs while checking the key. If the key is invalid or an error occurred, the reason code can be obtained using ERR_get_error(3).

  get_ex_data(index: int) → Any
  private_decrypt(data: bytes, padding: int) → bytes | None
  private_encrypt(data: bytes, padding: int) → bytes
  pub() → Tuple[bytes, bytes]
  public_decrypt(data: bytes, padding: int) → bytes | None
  public_encrypt(data: bytes, padding: int) → bytes
  save_key(file: str | bytes, cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable[[...], ~typing.Any] = <function passphrase_callback>) → int

    Save the key pair to a file in PEM format.

    Parameters:

      - file – Name of file to save key to.

      - cipher – Symmetric cipher to protect the key. The default cipher is ‘aes_128_cbc’. If cipher is None, then the key is saved in the clear.

      - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key. The default is util.passphrase_callback.

  save_key_bio(bio: ~M2Crypto.BIO.BIO, cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable[[...], ~typing.Any] = <function passphrase_callback>) → int

    Save the key pair to an M2Crypto.BIO.BIO object in PEM format.

    Parameters:

      - bio – M2Crypto.BIO.BIO object to save key to.

      - cipher – Symmetric cipher to protect the key. The default cipher is ‘aes_128_cbc’. If cipher is None, then the key is saved in the clear.

      - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key. The default is util.passphrase_callback.

  save_key_der(file: str | bytes) → int

    Save the key pair to a file in DER format.

    Parameters:

      file – Filename to save key to

  save_key_der_bio(bio: BIO) → int

    Save the key pair to an M2Crypto.BIO.BIO object in DER format.

    Parameters:

      bio – M2Crypto.BIO.BIO object to save key to.

  save_pem(file: str | bytes, cipher: str | None = 'aes_128_cbc', callback: ~typing.Callable[[...], ~typing.Any] = <function passphrase_callback>) → int

    Save the key pair to a file in PEM format.

    Parameters:

      - file – Name of file to save key to.

      - cipher – Symmetric cipher to protect the key. The default cipher is ‘aes_128_cbc’. If cipher is None, then the key is saved in the clear.

      - callback – A Python callable object that is invoked to acquire a passphrase with which to protect the key. The default is util.passphrase_callback.

  save_pub_key(file: str | bytes) → int

    Save the public key to a file in PEM format.

    Parameters:

      file – Name of file to save key to.

  save_pub_key_bio(bio: BIO) → int

    Save the public key to an M2Crypto.BIO.BIO object in PEM format.

    Parameters:

      bio – M2Crypto.BIO.BIO object to save key to.

  set_ex_data(index: int, data: Any) → int
  sign(digest: bytes, algo: str = 'sha256') → bytes

    Signs a digest with the private key

    Parameters:

      - digest – A digest created by using the digest method

      - algo – The method that created the digest. Legal values like ‘sha1’,’sha224’, ‘sha256’, ‘ripemd160’, and ‘md5’.

    Returns:

      a string which is the signature

  sign_rsassa_pss(digest: bytes, algo: str = 'sha256', salt_length: int = 20) → bytes

    Signs a digest with the private key using RSASSA-PSS

    Parameters:

      - digest – A digest created by using the digest method

      - salt_length – The length of the salt to use

      - algo – The hash algorithm to use Legal values like ‘sha1’,’sha224’, ‘sha256’, ‘ripemd160’, and ‘md5’.

    Returns:

      a string which is the signature

  verify(data: bytes, signature: bytes, algo: str = 'sha256') → int

    Verifies the signature with the public key

    Parameters:

      - data – Data that has been signed

      - signature – The signature signed with the private key

      - algo – The method use to create digest from the data before it was signed. Legal values like ‘sha1’,’sha224’, ‘sha256’, ‘ripemd160’, and ‘md5’.

    Returns:

      1 or 0, depending on whether the signature was verified or not.

  verify_rsassa_pss(data: bytes, signature: bytes, algo: str = 'sha256', salt_length: int = 20) → int

    Verifies the signature RSASSA-PSS

    Parameters:

      - data – Data that has been signed

      - signature – The signature signed with RSASSA-PSS

      - salt_length – The length of the salt that was used

      - algo – The hash algorithm to use Legal values are for example ‘sha1’,’sha224’, ‘sha256’, ‘ripemd160’, and ‘md5’.

    Returns:

      1 or 0, depending on whether the signature was verified or not.

exception M2Crypto.RSA.RSAError

  Bases: `Exception`

class M2Crypto.RSA.RSA_pub(rsa: RSA, _pyfree: int = 0)

  Bases: `RSA`

  Object interface to an RSA public key.

  check_key() → int

    Validate RSA keys.

    It checks that p and q are in fact prime, and that n = p*q.

    Returns:

      returns 1 if rsa is a valid RSA key, and 0 otherwise. -1 is returned if an error occurs while checking the key. If the key is invalid or an error occurred, the reason code can be obtained using ERR_get_error(3).

  private_decrypt(*argv: Any) → None
  private_encrypt(*argv: Any) → None
  save_key(file: str | bytes, *args: Any, **kw: Any) → int

    Save public key to file.

  save_key_bio(bio: BIO, *args: Any, **kw: Any) → int

    Save public key to BIO.

M2Crypto.RSA.gen_key(bits: int, e: int, callback: ~typing.Callable[[int, int], int] = <function keygen_callback>) → RSA

  Generate an RSA key pair.

  Parameters:

    - bits – Key length, in bits.

    - e – The RSA public exponent.

    - callback – A Python callable object that is invoked during key generation; its usual purpose is to provide visual feedback. The default callback is keygen_callback.

  Returns:

    M2Crypto.RSA.RSA object.

M2Crypto.RSA.keygen_callback(p: int, n: int) → int

  Default callback for gen_key().

M2Crypto.RSA.load_key(file: str | bytes, callback: ~typing.Callable[[...], ~typing.Any] = <function passphrase_callback>) → RSA

  Load an RSA key pair from file.

  Parameters:

    - file – Name of file containing RSA public key in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to unlock the key. The default is util.passphrase_callback.

  Returns:

    M2Crypto.RSA.RSA object.

M2Crypto.RSA.load_key_bio(bio: ~M2Crypto.BIO.BIO, callback: ~typing.Callable[[...], ~typing.Any] = <function passphrase_callback>) → RSA

  Load an RSA key pair from an M2Crypto.BIO.BIO object.

  Parameters:

    - bio – M2Crypto.BIO.BIO object containing RSA key pair in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to unlock the key. The default is util.passphrase_callback.

  Returns:

    M2Crypto.RSA.RSA object.

M2Crypto.RSA.load_key_string(string: str | bytes, callback: ~typing.Callable[[...], ~typing.Any] = <function passphrase_callback>) → RSA

  Load an RSA key pair from a string.

  Parameters:

    - string – String containing RSA key pair in PEM format.

    - callback – A Python callable object that is invoked to acquire a passphrase with which to unlock the key. The default is util.passphrase_callback.

  Returns:

    M2Crypto.RSA.RSA object.

M2Crypto.RSA.load_pub_key(file: str | bytes) → RSA_pub

  Load an RSA public key from file.

  Parameters:

    file – Name of file containing RSA public key in PEM format.

  Returns:

    M2Crypto.RSA.RSA_pub object.

M2Crypto.RSA.load_pub_key_bio(bio: BIO) → RSA_pub

  Load an RSA public key from an M2Crypto.BIO.BIO object.

  Parameters:

    bio – M2Crypto.BIO.BIO object containing RSA public key in PEM format.

  Returns:

    M2Crypto.RSA.RSA_pub object.

M2Crypto.RSA.new_pub_key(e_n: Tuple[bytes, bytes]) → RSA_pub

  Instantiate an RSA_pub object from an (e, n) tuple.

  Parameters:

    - e – The RSA public exponent; it is a string in OpenSSL’s MPINT format - 4-byte big-endian bit-count followed by the appropriate number of bits.

    - n – The RSA composite of primes; it is a string in OpenSSL’s MPINT format - 4-byte big-endian bit-count followed by the appropriate number of bits.

  Returns:

    M2Crypto.RSA.RSA_pub object.

M2Crypto.RSA.rsa_error() → None

## `Rand` Module

M2Crypto wrapper for OpenSSL PRNG. Requires OpenSSL 0.9.5 and above.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved. Copyright (c) 2014-2017 Matej Cepl. All rights reserved.

See LICENCE for the license information.

M2Crypto.Rand.load_file(filename: str | bytes, max_bytes: int) → int

  Read a number of bytes from file filename and adds them to the PRNG.

  If max_bytes is non-negative, up to to max_bytes are read; starting with OpenSSL 0.9.5, if max_bytes is -1, the complete file is read.

  Parameters:

    - filename

    - max_bytes

  Returns:

    the number of bytes read.

M2Crypto.Rand.rand_add(blob: bytes, entropy: float) → None

  Mixes blob into the PRNG state.

  Parameters:

    - blob – added data

    - entropy – (the lower bound of) an estimate of how much randomness is contained in blob, measured in bytes.

  Thus, if the data at buf are unpredictable to an adversary, this increases the uncertainty about the state and makes the PRNG output less predictable. Suitable input comes from user interaction (random key presses, mouse movements) and certain hardware events.

  Details about sources of randomness and how to estimate their entropy can be found in the literature, e.g. RFC 1750.

M2Crypto.Rand.rand_bytes(num: int) → bytes

  Return n cryptographically strong pseudo-random bytes.

  An error occurs if the PRNG has not been seeded with enough randomness to ensure an unpredictable byte sequence.

  Parameters:

    num – number of bytes to be returned

  Returns:

    random bytes

M2Crypto.Rand.rand_file_name() → str

  Generate a default path for the random seed file.

  Returns:

    string with the filename. The seed file is $RANDFILE if that environment variable is set, $HOME/.rnd otherwise. If $HOME is not set either, an error occurs.

M2Crypto.Rand.rand_pseudo_bytes(num: int) → Tuple[bytes, int]

  Return num pseudo-random bytes into buf.

  Pseudo-random byte sequences generated by this method will be unique if they are of sufficient length, but are not necessarily unpredictable. They can be used for non-cryptographic purposes and for certain purposes in cryptographic protocols, but usually not for key generation etc.

  Output of the function is mixed into the entropy pool before retrieving the new pseudo-random bytes unless disabled at compile time (see FAQ).

  Parameters:

    num – number of bytes to be returned

  Returns:

    random bytes

M2Crypto.Rand.rand_seed(seed: bytes) → None

  Equivalent to rand_add() when len(seed) == entropy.

  Parameters:

    seed – added data (see description at rand_add)

M2Crypto.Rand.rand_status() → int

  Check whether there is enough entropy in PRNG.

  Returns:

    1 if the PRNG has been seeded with enough data, 0 otherwise.

M2Crypto.Rand.save_file(filename: str | bytes) → int

  Write a number of random bytes (currently 1024) to file.

  The file then can be used to initialize the PRNG by calling load_file() in a later session.

  Parameters:

    filename

  Returns:

    returns the number of bytes written, and -1 if the bytes written were generated without appropriate seed.

## `SMIME` Module

M2Crypto wrapper for OpenSSL S/MIME API.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

class M2Crypto.SMIME.Cipher(algo: str)

  Bases: `object`

  Object interface to EVP_CIPHER without all the frills of M2Crypto.EVP.Cipher.

class M2Crypto.SMIME.PKCS7(pkcs7: PKCS7 | None = None, _pyfree: int = 0)

  Bases: `object`

  get0_signers(certs: X509_Stack, flags: int = 0) → X509_Stack
  type(text_name: int = 0) → int | str
  write(bio: BIO) → int
  write_der(bio: BIO) → int

exception M2Crypto.SMIME.PKCS7_Error

  Bases: `Exception`

class M2Crypto.SMIME.SMIME

  Bases: `object`

  decrypt(pkcs7: PKCS7, flags: int = 0) → bytes | None
  encrypt(data_bio: BIO, flags: int = 0) → PKCS7
  load_key(keyfile: str | bytes, certfile: str | bytes | None = None, callback: ~typing.Callable = <function passphrase_callback>) → None
  load_key_bio(keybio: ~M2Crypto.BIO.BIO, certbio: ~M2Crypto.BIO.BIO | None = None, callback: ~typing.Callable = <function passphrase_callback>) → None
  set_cipher(cipher: Cipher) → None
  set_x509_stack(stack: X509_Stack) → None
  set_x509_store(store: X509_Store) → None
  sign(data_bio: BIO, flags: int = 0, algo: str = 'sha256') → PKCS7
  unset_cipher() → None
  unset_key() → None
  unset_x509_stack() → None
  unset_x509_store() → None
  verify(pkcs7: PKCS7, data_bio: BIO | None = None, flags: int = 0) → bytes | None
  write(out_bio: BIO, pkcs7: PKCS7, data_bio: BIO | None = None, flags: int = 0) → int

exception M2Crypto.SMIME.SMIME_Error

  Bases: `Exception`

M2Crypto.SMIME.load_pkcs7(p7file: str | bytes) → PKCS7

M2Crypto.SMIME.load_pkcs7_bio(p7_bio: BIO) → PKCS7

M2Crypto.SMIME.load_pkcs7_bio_der(p7_bio: BIO) → PKCS7

M2Crypto.SMIME.load_pkcs7_der(p7file: str | bytes) → PKCS7

M2Crypto.SMIME.smime_load_pkcs7(p7file: str | bytes) → Tuple[PKCS7, BIO | None]

M2Crypto.SMIME.smime_load_pkcs7_bio(p7_bio: BIO) → Tuple[PKCS7, BIO | None]

M2Crypto.SMIME.text_crlf(text: bytes) → bytes

M2Crypto.SMIME.text_crlf_bio(bio_in: BIO) → BIO

## `X509` Module

M2Crypto wrapper for OpenSSL X509 API.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

Portions created by Open Source Applications Foundation (OSAF) are Copyright (C) 2004-2007 OSAF. All Rights Reserved. Author: Heikki Toivonen

class M2Crypto.X509.CRL(crl: X509_CRL | None = None, _pyfree: int = 0)

  Bases: `object`

  X509 Certificate Revocation List

  as_text() → str

    Return CRL in PEM format in a string.

    Returns:

      String containing the CRL in PEM format.

class M2Crypto.X509.Request(req: X509_REQ | None = None, _pyfree: int = 0)

  Bases: `object`

  X509 Certificate Request.

  add_extensions(ext_stack: X509_Extension_Stack) → int

    Add X509 extensions to this request.

    Parameters:

      ext_stack – Stack of extensions to add.

    Returns:

      1 for success and 0 for failure

  as_der() → bytes
  as_pem() → bytes
  as_text() → str
  get_pubkey() → PKey

    Get the public key for the request.

    Returns:

      Public key from the request.

  get_subject() → X509_Name
  get_version() → int

    Get the version of the request. :return: Version number.

  save(filename: str, format: int = 1) → int

    Saves X.509 certificate request to a file. Default output format is PEM.

    Parameters:

      filename –

      Name of the file the request will be s: aved to.

      request. Either FORMAT_PEM or FORMAT_DER to save in PEM or DER format. Raises V: a lueError if an unknown format is used.

    Returns:

      1 for success, 0 for failure. The error code can be obtained by ERR_get_error.

  save_pem(filename: str) → int
  set_pubkey(pkey: PKey) → int

    Set the public key for the request.

    Parameters:

      pkey – Public key

    Returns:

      Return 1 for success and 0 for failure.

  set_subject(name: X509_Name) → int

    Set subject name.

    Parameters:

      name – subjectName field.

    Returns:

      1 for success and 0 for failure

  set_subject_name(name: X509_Name) → int

    Set subject name.

    Parameters:

      name – subjectName field.

    Returns:

      1 for success and 0 for failure

  set_version(ver: int) → int

    Set the version of the request. :param ver: Version number. :return: 1 for success, 0 for failure.

  sign(pkey: PKey, md: str) → int
    Parameters:

      - pkey – PKey to be signed

      - md – used algorigthm

    Returns:

      1 for success and 0 for failure

  verify(pkey: PKey) → int
    Parameters:

      pkey – PKey to be verified

    Returns:

      1 for success and 0 for failure

class M2Crypto.X509.X509(x509: X509 | None = None, _pyfree: int = 0)

  Bases: `object`

  X.509 Certificate

  add_ext(ext: X509_Extension) → int

    Add X509 extension to this certificate.

    Parameters:

      ext – Extension

    :return 1 for success and 0 for failure

  add_subject_key_identifier() → int

    Adds a Subject Key Identifier (SKI) extension to the certificate, calculating the key identifier from the certificate’s public key.

    This bypasses the error-prone use of ‘subjectKeyIdentifier’, ‘hash’ in new_extension, which requires a pre-configured OpenSSL context.

    Returns:

      1 for success and 0 for failure.

  as_der() → bytes
  as_pem() → bytes
  as_text() → str
  check_ca() → int

    Check if the certificate is a Certificate Authority (CA) certificate.

    Returns:

      0 if the certificate is not CA, nonzero otherwise.

    Requires:

      OpenSSL 0.9.8 or newer

  check_purpose(id: int, ca: int) → int

    Check if the certificate’s purpose matches the asked purpose.

    Parameters:

      - id – Purpose id. See X509_PURPOSE_* constants.

      - ca – 1 if the certificate should be CA, 0 otherwise.

    Returns:

      0 if the certificate purpose does not match, nonzero otherwise.

  get_ext(name: str) → X509_Extension

    Get X509 extension by name.

    Parameters:

      name – Name of the extension

    Returns:

      X509_Extension

  get_ext_at(index: int) → X509_Extension

    Get X509 extension by index.

    Parameters:

      index – Name of the extension

    Returns:

      X509_Extension

  get_ext_count() → int

    Get X509 extension count.

  get_fingerprint(md: str = 'sha1') → str

    Get the fingerprint of the certificate.

    Parameters:

      md – Message digest algorithm to use.

    Returns:

      String containing the fingerprint in hex format.

  get_issuer() → X509_Name
  get_not_after() → ASN1_TIME
  get_not_before() → ASN1_TIME
  get_pubkey() → PKey
  get_serial_number() → int
  get_subject() → X509_Name
  get_version() → int
  save(filename: str, format: int = 1) → int

    Saves X.509 certificate to a file. Default output format is PEM.

    Parameters:

      - filename – Name of the file the cert will be saved to.

      - format – Controls what output format is used to save the cert. Either FORMAT_PEM or FORMAT_DER to save in PEM or DER format. Raises a ValueError if an unknow format is used.

    Returns:

      1 for success or 0 for failure

  save_pem(filename: str) → int
    Parameters:

      filename – name of the file to be loaded

    Returns:

      1 for success or 0 for failure

  set_issuer(name: X509_Name) → int
  set_issuer_name(name: X509_Name) → int
  set_not_after(asn1_time: ASN1_TIME) → int
    Returns:

      1 on success, 0 on failure

  set_not_before(asn1_time: ASN1_TIME) → int
    Returns:

      1 on success, 0 on failure

  set_pubkey(pkey: PKey) → int

    Set the public key for the certificate

    Parameters:

      pkey – Public key

    :return 1 for success and 0 for failure

  set_serial_number(serial: int) → int

    Set serial number.

    Parameters:

      serial – Serial number.

    :return 1 for success and 0 for failure.

  set_subject(name: X509_Name) → int
    Returns:

      1 on success, 0 on failure

  set_subject_name(name: X509_Name) → int
    Returns:

      1 on success, 0 on failure

  set_version(version: int) → int

    Set version of the certificate.

    Parameters:

      version – Version number.

    Returns:

      Returns 0 on failure.

  sign(pkey: PKey, md: str) → int

    Sign the certificate.

    Parameters:

      - pkey – Public key

      - md – Message digest algorithm to use for signing, for example ‘sha1’.

    :return int

  verify(pkey: PKey | None = None) → int

exception M2Crypto.X509.X509Error

  Bases: `ValueError`

class M2Crypto.X509.X509_Extension(x509_ext_ptr: X509_EXTENSION | None = None, _pyfree: int = 1)

  Bases: `object`

  X509 Extension

  get_critical() → int

    Return whether or not this is a critical extension.

    Returns:

      Nonzero if this is a critical extension.

  get_name() → str

    Get the extension name, for example ‘subjectAltName’.

  get_value(flag: int = 0, indent: int = 0) → str

    Get the extension value, for example ‘DNS:www.example.com’.

    Parameters:

      - flag – Flag to control what and how to print.

      - indent – How many spaces to print before actual value.

  set_critical(critical: int = 1) → int

    Mark this extension critical or noncritical. By default an extension is not critical.

    Parameters:

      critical – Nonzero sets this extension as critical. Calling this method without arguments will set this extension to critical.

    Returns:

      1 for success, 0 for failure

class M2Crypto.X509.X509_Extension_Stack(stack: List[X509_EXTENSION] | None = None, _pyfree: int = 0)

  Bases: `object`

  X509 Extension Stack

  Warning:

    Do not modify the underlying OpenSSL stack except through this interface, or use any OpenSSL functions that do so indirectly. Doing so will get the OpenSSL stack and the internal pystack of this class out of sync, leading to python memory leaks, exceptions or even python crashes!

  pop() → X509_Extension | None

    Pop X509_Extension object from the stack.

    Returns:

      X509_Extension object that was popped, or None if there is nothing to pop.

  push(x509_ext: X509_Extension) → int

    Push X509_Extension object onto the stack.

    Parameters:

      x509_ext – X509_Extension object to be pushed onto the stack.

    Returns:

      The number of extensions on the stack.

class M2Crypto.X509.X509_Name(x509_name: X509_NAME | None = None, _pyfree: int = 0)

  Bases: `object`

  X509 Name

  add_entry_by_txt(field: str, type: int, entry: str | bytes, len: int, loc: int, set: int) → int

    Add X509_Name field whose name is identified by its name.

    Parameters:

      - field – name of the entry

      - type – use MBSTRING_ASC or MBSTRING_UTF8 (or standard ASN1 type like V_ASN1_IA5STRING)

      - entry – value

      - len – buf_len of the entry (-1 and the length is computed automagically)

      - loc – determines the index where the new entry is inserted: if it is -1 it is appended.

      - set – determines how the new type is added. If it is zero a new RDN is created. If set is -1 or 1 it is added to the previous or next RDN structure respectively. This will then be a multivalued RDN: since multivalues RDNs are very seldom used set is almost always set to zero.

    Returns:

      1 for success of 0 if an error occurred.

  as_der() → bytes
  as_hash() → int
  as_text(indent: int = 0, flags: int = 0) → str

    as_text returns the name as a string.

    Parameters:

      - indent – Each line in multiline format is indented by this many spaces.

      - flags – Flags that control how the output should be formatted.

  entry_count() → int
  get_entries_by_nid(nid: int) → List[X509_Name_Entry]

    Retrieve the next index matching nid.

    Parameters:

      nid – name of the entry (as m2.NID* constants)

    Returns:

      list of X509_Name_Entry items

  nid = {'C': 14, 'CN': 13, 'Email': 48, 'GN': 99, 'L': 15, 'O': 17, 'OU': 18, 'SN': 100, 'SP': 16, 'ST': 16, 'commonName': 13, 'emailAddress': 48, 'givenName': 99, 'localityName': 15, 'organizationName': 17, 'organizationUnitName': 18, 'serialNumber': 105, 'stateOrProvinceName': 16, 'surname': 100}

class M2Crypto.X509.X509_Name_Entry(x509_name_entry: X509_NAME_ENTRY, _pyfree: int = 0)

  Bases: `object`

  X509 Name Entry

  create_by_txt(field: str, type: int, entry: bytes, length: int) → X509_NAME_ENTRY

    Creates and returns a new X509_NAME_ENTRY object. Note: This is a factory method that uses an existing instance’s pointer space in a confusing way. It should likely be a static or class method for clarity. The corrected implementation below makes it work as written.

  get_data() → ASN1_String
  get_object() → ASN1_Object
  set_data(data: bytes, type: int = 4097) → int

    Sets the field value.

    Parameters:

      data – data in a binary form to be set

    Returns:

      0 on failure, 1 on success

  set_object(asn1obj: ASN1_Object) → int

    Sets the field name to asn1obj

    Parameters:

      asn1obj

    Returns:

      0 on failure, 1 on success

class M2Crypto.X509.X509_Stack(stack: List[X509] | None = None, _pyfree: int = 0, _pyfree_x509: int = 0)

  Bases: `object`

  X509 Stack

  Warning:

    Do not modify the underlying OpenSSL stack except through this interface, or use any OpenSSL functions that do so indirectly. Doing so will get the OpenSSL stack and the internal pystack of this class out of sync, leading to python memory leaks, exceptions or even python crashes!

  as_der() → bytes

    Return the stack as a DER encoded string

  pop() → X509 | None

    pop a certificate from the stack.

    Returns:

      X509 object that was popped, or None if there is nothing to pop.

  push(x509: X509) → int

    push an X509 certificate onto the stack.

    Parameters:

      x509 – X509 object.

    Returns:

      The number of X509 objects currently on the stack.

class M2Crypto.X509.X509_Store(store: X509_STORE | None = None, _pyfree: int = 0)

  Bases: `object`

  X509 Store

  add_cert(x509: X509) → int

    Add X509 certificate to the store.

  add_x509(x509: X509) → int

    Add X509 certificate to the store.

  load_info(file: str) → int
    Parameters:

      file – filename

    Returns:

      1 on success, 0 on failure

  load_locations(file: str) → int
    Parameters:

      file – filename

    Returns:

      1 on success, 0 on failure

  set_flags(flags: int) → int

    Set the verification flags for the X509Store Wrapper over OpenSSL X509_STORE_set_flags()

    Parameters:

      flags – VERIFICATION FLAGS section of the X509_VERIFY_PARAM_set_flags man page has a complete description of values the flags parameter can take. Their M2Crypto equivalent is transformed following the pattern: “X509_V_FLAG_XYZ” -> lowercase(“VERIFY_XYZ”)

  set_verify_cb(callback: Callable[[int, X509_STORE_CTX], int] | None = None) → None

    Set callback which will be called when the store is verified. Wrapper over OpenSSL X509_STORE_set_verify_cb().

    Parameters:

      callback – Callable to specify verification options. Type of the callable must be: (int, X509_Store_Context) -> int. If None: set the standard options.

    Note:

      compile-time or run-time errors in the callback would result in mysterious errors during verification, which could be hard to trace.

    Note:

      Python exceptions raised in callbacks do not propagate to verify() call.

    Returns:

      None

class M2Crypto.X509.X509_Store_Context(x509_store_ctx: X509_STORE_CTX, _pyfree: int = 0)

  Bases: `object`

  X509 Store Context

  get1_chain() → X509_Stack

    Get certificate chain.

    Returns:

      Reference counted (i.e. safe to use even after the store context goes away) stack of certificates in the chain as X509_Stack.

  get_current_cert() → X509 | None

    Get current X.509 certificate.

    Warning:

      The returned certificate is NOT refcounted, so you can not rely on it being valid once the store context goes away or is modified.

  get_error() → int

    Get error code.

  get_error_depth() → int

    Get error depth.

M2Crypto.X509.load_cert(file: str | bytes, format: int = 1) → X509

  Load certificate from file.

  Parameters:

    - file – Name of file containing certificate in either DER or PEM format.

    - format – Describes the format of the file to be loaded, either PEM or DER.

  Returns:

    M2Crypto.X509.X509 object.

M2Crypto.X509.load_cert_bio(bio: BIO, format: int = 1) → X509

  Load certificate from a bio.

  Parameters:

    - bio – BIO pointing at a certificate in either DER or PEM format.

    - format – Describes the format of the cert to be loaded, either PEM or DER (via constants FORMAT_PEM and FORMAT_FORMAT_DER)

  Returns:

    M2Crypto.X509.X509 object.

M2Crypto.X509.load_cert_der_string(cert_str: str | bytes) → X509

  Load certificate from a cert_str.

  Parameters:

    cert_str – String containing a certificate in DER format.

  Returns:

    M2Crypto.X509.X509 object.

M2Crypto.X509.load_cert_string(string: str | bytes, format: int = 1) → X509

  Load certificate from a cert_str.

  Parameters:

    - cert_str – String containing a certificate in either DER or PEM format.

    - format – Describes the format of the cert to be loaded, either PEM or DER (via constants FORMAT_PEM and FORMAT_FORMAT_DER)

  Returns:

    M2Crypto.X509.X509 object.

M2Crypto.X509.load_crl(file: str) → CRL

  Load CRL from file.

  Parameters:

    file – Name of file containing CRL in PEM format.

  Returns:

    M2Crypto.X509.CRL object.

M2Crypto.X509.load_request(file: str | bytes, format: int = 1) → Request

  Load certificate request from file.

  Parameters:

    - file – Name of file containing certificate request in either PEM or DER format.

    - format – Describes the format of the file to be loaded, either PEM or DER. (using constants FORMAT_PEM and FORMAT_DER)

  Returns:

    Request object.

M2Crypto.X509.load_request_bio(bio: BIO, format: int = 1) → Request

  Load certificate request from a bio.

  Parameters:

    - bio – BIO pointing at a certificate request in either DER or PEM format.

    - format – Describes the format of the request to be loaded, either PEM or DER. (using constants FORMAT_PEM and FORMAT_DER)

  Returns:

    M2Crypto.X509.Request object.

M2Crypto.X509.load_request_der_string(cert_str: str | bytes) → Request

  Load certificate request from a cert_str.

  Parameters:

    cert_str – String containing a certificate request in DER format.

  Returns:

    M2Crypto.X509.Request object.

M2Crypto.X509.load_request_string(string: str | bytes, format: int = 1) → Request

  Load certificate request from a cert_str.

  Parameters:

    - cert_str – String containing a certificate request in either DER or PEM format.

    - format – Describes the format of the request to be loaded, either PEM or DER. (using constants FORMAT_PEM and FORMAT_DER)

  Returns:

    M2Crypto.X509.Request object.

M2Crypto.X509.new_extension(name: str, value: str, critical: int = 0, _pyfree: int = 1, pkey: PKey | None = None) → X509_Extension

  Create a new X509_Extension instance using OpenSSL’s internal V3 extension configuration.

  This method relies on the OpenSSL ‘x509v3_ext_conf’ function to parse a textual extension name and value into an X509_EXTENSION structure.

  Parameters:

    - name – The short name of the extension (e.g., ‘subjectAltName’, ‘basicConstraints’).

    - value – The value string for the extension (e.g., ‘DNS:example.com’, ‘CA:TRUE’). For complex extensions like ‘subjectKeyIdentifier’, the value often specifies the content, such as ‘hash’ to compute the hash of the subject’s public key.

    - critical – Set to 1 to mark the extension as critical, 0 otherwise (default is 0).

    - _pyfree – Internal flag (default 1).

    - pkey – Optional EVP.PKey object. Required when the extension value requires an associated public key to be computed, such as when: - name is ‘subjectKeyIdentifier’ and value is ‘hash’. If an extension requires a public key context and pkey is None, an X509Error will be raised to prevent a Segmentation Fault (SIGSEGV) in modern OpenSSL versions by accessing an uninitialized context pointer.

  Returns:

    A new X509_Extension instance.

  Raises:

    X509Error – If the extension cannot be created (e.g., invalid name/value) or if a required context (pkey) is missing.

M2Crypto.X509.new_stack_from_der(der_string: bytes) → X509_Stack

  Create a new X509_Stack from DER string.

M2Crypto.X509.x509_store_default_cb(ok: int, ctx: X509_STORE_CTX) → int

## `callback` Module

Deprecated, use the util module instead.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

## `ftpslib` Module

M2Crypto client-side FTP/TLS.

This implementation complies with draft-murray-auth-ftp-ssl-07.txt.

Example:

> from M2Crypto import ftpslib f = ftpslib.FTP_TLS() f.connect(‘ftp.example.com’, 21) f.auth_tls() f.set_pasv(0) f.login(‘username’, ‘password’) f.retrlines(‘LIST’) # Output: # -rw-rw-r– 1 0 198 2326 Jul 3 1996 apache_pb.gif # drwxrwxr-x 7 0 198 1536 Oct 10 2000 manual # drwxrwxr-x 2 0 198 512 Oct 31 2000 modpy # drwxrwxr-x 2 0 198 512 Oct 31 2000 bobo # … # ‘226 Transfer complete’ f.quit() # ‘221 Goodbye.’

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

class M2Crypto.ftpslib.FTP_TLS(host=None, ssl_ctx=None)

  Bases: `FTP`

  Python OO interface to client-side FTP/TLS.

  auth_ssl()

    Secure the control connection per AUTH SSL, aka AUTH TLS-P.

  auth_tls()

    Secure the control connection per AUTH TLS, aka AUTH TLS-C.

  ntransfercmd(cmd, rest=None)

    Initiate a data transfer.

  prot_c()

    Set up data connection in the clear.

  prot_p()

    Set up secure data connection.

## `httpslib` Module

class M2Crypto.httpslib.HTTPSConnection(host: str, port: int | None = None, strict: bool | None = None, ssl_conn_cls: ~typing.Type[~M2Crypto.SSL.Connection.Connection] = <class 'M2Crypto.SSL.Connection.Connection'>, **ssl)

  Bases: `HTTPConnection`

  This class allows communication via SSL using M2Crypto.

  close() → None

    Close the connection to the HTTP server.

  connect() → None

    Connect to the host and port specified in __init__.

  default_port = 443
  get_session() → Session | None
  set_session(session: Session) → None
  sock: Connection

class M2Crypto.httpslib.ProxyHTTPSConnection(host: str, port: int | None = None, strict: bool | None = None, username: str | bytes | None = None, password: str | bytes | None = None, **ssl)

  Bases: `HTTPSConnection`

  An HTTPS Connection that uses a proxy and the CONNECT request.

  When the connection is initiated, CONNECT is first sent to the proxy (along with authorization headers, if supplied). If successful, an SSL connection will be established over the socket through the proxy and to the target host.

  Finally, the actual request is sent over the SSL connection tunneling through the proxy.

  connect() → None

    Connect to the host and port specified in __init__.

  endheaders(*args, **kwargs) → None

    Indicate that the last header line has been sent to the server.

    This method sends the request to the server. The optional message_body argument can be used to pass a message body associated with the request.

  putheader(header: str | bytes, *values: Any) → None

    Send a request header line to the server.

    For example: h.putheader(‘Accept’, ‘text/html’)

  putrequest(method: str | bytes, url: str | bytes, skip_host: bool = False, skip_accept_encoding: bool = False) → None

    putrequest is called before connect, so can interpret url and get real host/port to be used to make CONNECT request to proxy

  ssl_ctx: Context

## `m2` Module

M2Crypto low level OpenSSL wrapper functions.

m2 is the low level wrapper for OpenSSL functions. Typically you would not need to use these directly, since these will be called by the higher level objects you should try to use instead.

Naming conventions: All functions wrapped by m2 are all lower case, words separated by underscores.

Examples:

OpenSSL M2Crypto

X509_get_version m2.x509_get_version X509_get_notBefore m2.x509_get_not_before X509_REQ_verify m2.x509_req_verify

Exceptions to naming rules:

XXX TDB

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

Portions created by Open Source Applications Foundation (OSAF) are Copyright (C) 2004 OSAF. All Rights Reserved.

## `m2crypto` Module

## `m2urllib` Module

M2Crypto enhancement to Python’s urllib for handling ‘https’ url’s.

FIXME: it is questionable whether we need this old-style module at all. urllib (not urllib2) is in Python 3 support just as a legacy API.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

class M2Crypto.m2urllib.URLopener

  Bases: `object`

  msg = 'Python 3.14 does not support URLopener any more.'
  open_https()

## `m2urllib2` Module

M2Crypto enhancement to Python’s urllib2 for handling ‘https’ url’s.

Code from urllib2 is Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; All Rights Reserved

Summary of changes:

  - Use an HTTPSProxyConnection if the request is going through a proxy.

  - Add the SSL context to the https connection when performing https_open.

  - Add the M2Crypto HTTPSHandler when building a default opener.

class M2Crypto.m2urllib2.HTTPSHandler(ssl_context: ~M2Crypto.SSL.Context.Context | None = None, ssl_conn_cls: ~typing.Type[~M2Crypto.SSL.Connection.Connection] = <class 'M2Crypto.m2urllib2.RefCountingSSLConnection'>)

  Bases: `AbstractHTTPHandler`

  https_open(req: Request) → addinfourl

    Return an addinfourl object for the request, using http_class.

    http_class must implement the HTTPConnection API from httplib. The addinfourl return value is a file-like object. It also has methods and attributes including:

    > - info(): return a mimetools.Message object for the headers

    > - geturl(): return the original request URL

    > - code: HTTP status code

  https_request(request)

class M2Crypto.m2urllib2.RefCountingSSLConnection(*args, **kwargs)

  Bases: `Connection`

  A reference counting SSL connection.

  It can be wrapped into a socket._fileobject or socket.SocketIO instance. If the wrapping object is closed or subject to garbage collection, this SSL connection is only shut down if there are no more references, which were created by RefCountingSSLConnection.makefile, to it.

  close()

    Close the connection. This is idempotent.

    The original ref-counting logic has been bypassed for this direct call to provide a simpler, more robust shutdown path for the primary use case.

  makefile(mode='rb', bufsize=-1)

M2Crypto.m2urllib2.build_opener(ssl_context: Context | None = None, *handlers) → OpenerDirector

  Create an opener object from a list of handlers.

  The opener will use several default handlers, including support for HTTP and FTP.

  If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used.

## `m2xmlrpclib` Module

M2Crypto enhancement to xmlrpclib.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

class M2Crypto.m2xmlrpclib.SSL_Transport(ssl_context: Context | None = None, *args, **kw)

  Bases: `Transport`

  request(host: str | Tuple[str, Dict[str, str]], handler: str, request_body: bytes | bytearray, verbose: int = 0) → Tuple[Any, ...]
  static splitport(host)

    splitport(‘host:port’) –> ‘host’, ‘port’.

  static splituser(host)

    splituser(‘user[:passwd]@host[:port]’) –> ‘user[:passwd]’, ‘host[:port]’.

  user_agent = 'M2Crypto_XMLRPC/0.46.2 - Python-xmlrpc/3.14'

## `threading` Module

M2Crypto threading support, required for multithreaded applications.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.

M2Crypto.threading.cleanup() → None

  End and cleanup threading support.

M2Crypto.threading.init() → None

  Initialize threading support.

## `util` Module

M2Crypto utility routines.

NOTHING IN THIS MODULE IS GUARANTEED TO BE STABLE, USED ONLY FOR INTERNAL PURPOSES OF M2CRYPTO.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

Portions created by Open Source Applications Foundation (OSAF) are Copyright (C) 2004 OSAF. All Rights Reserved.

exception M2Crypto.util.UtilError

  Bases: `Exception`

M2Crypto.util.bin_to_hex(b: bytes) → str

M2Crypto.util.expectedFailureIf(condition: bool) → Callable

  The test is marked as an expectedFailure if the condition is satisfied.

M2Crypto.util.genparam_callback(p: int, n: int) → int

M2Crypto.util.is_32bit() → bool

M2Crypto.util.no_passphrase_callback(*args) → str

M2Crypto.util.octx_to_num(x: bytes) → int

M2Crypto.util.passphrase_callback(v: bool, prompt1: str = 'Enter passphrase:', prompt2: str = 'Verify passphrase:') → str | None

M2Crypto.util.pkcs5_pad(data: str, blklen: int = 8) → str

M2Crypto.util.pkcs7_pad(data: str, blklen: int) → str

M2Crypto.util.quiet_genparam_callback(p: int, n: int) → int

## Subpackages

- SSL Package
  - `SSL` Package
  - `Checker` Module
    - `Checker`
      - `Checker.numericIpMatch`
    - `NoCertificate`
    - `SSLVerificationError`
    - `WrongCertificate`
    - `WrongHost`
  - `Cipher` Module
    - `Cipher`
      - `Cipher.cipher`
      - `Cipher.name()`
      - `Cipher.version()`
    - `Cipher_Stack`
      - `Cipher_Stack.stack`
  - `Connection` Module
    - `Connection`
      - `Connection.accept()`
      - `Connection.accept_ssl()`
      - `Connection.bind()`
      - `Connection.clear()`
      - `Connection.close()`
      - `Connection.closed`
      - `Connection.connect()`
      - `Connection.connect_ssl()`
      - `Connection.fileno()`
      - `Connection.flush()`
      - `Connection.get_cipher()`
      - `Connection.get_cipher_list()`
      - `Connection.get_ciphers()`
      - `Connection.get_context()`
      - `Connection.get_default_session_timeout()`
      - `Connection.get_peer_cert()`
      - `Connection.get_peer_cert_chain()`
      - `Connection.get_session()`
      - `Connection.get_shutdown()`
      - `Connection.get_socket_read_timeout()`
      - `Connection.get_socket_write_timeout()`
      - `Connection.get_state()`
      - `Connection.get_verify_depth()`
      - `Connection.get_verify_mode()`
      - `Connection.get_verify_result()`
      - `Connection.get_version()`
      - `Connection.getpeername()`
      - `Connection.getsockname()`
      - `Connection.getsockopt()`
      - `Connection.listen()`
      - `Connection.m2_bio_free()`
      - `Connection.m2_bio_noclose`
      - `Connection.m2_ssl_free()`
      - `Connection.makefile()`
      - `Connection.pending()`
      - `Connection.read()`
      - `Connection.readable()`
      - `Connection.readinto()`
      - `Connection.recv()`
      - `Connection.recv_into()`
      - `Connection.renegotiate()`
      - `Connection.send()`
      - `Connection.sendall()`
      - `Connection.set1_host()`
      - `Connection.set_accept_state()`
      - `Connection.set_bio()`
      - `Connection.set_cipher_list()`
      - `Connection.set_client_CA_list_from_context()`
      - `Connection.set_client_CA_list_from_file()`
      - `Connection.set_connect_state()`
      - `Connection.set_post_connection_check_callback()`
      - `Connection.set_session()`
      - `Connection.set_session_id_ctx()`
      - `Connection.set_shutdown()`
      - `Connection.set_socket_read_timeout()`
      - `Connection.set_socket_write_timeout()`
      - `Connection.set_ssl_close_flag()`
      - `Connection.set_tlsext_host_name()`
      - `Connection.setblocking()`
      - `Connection.setsockopt()`
      - `Connection.settimeout()`
      - `Connection.setup_addr()`
      - `Connection.setup_ssl()`
      - `Connection.shutdown()`
      - `Connection.ssl_get_error()`
      - `Connection.verify_ok()`
      - `Connection.writable()`
      - `Connection.write()`
  - `Context` Module
    - `Context`
      - `Context.add_session()`
      - `Context.close()`
      - `Context.get_allow_unknown_ca()`
      - `Context.get_cert_store()`
      - `Context.get_session_cache_mode()`
      - `Context.get_session_timeout()`
      - `Context.get_verify_depth()`
      - `Context.get_verify_mode()`
      - `Context.load_cert()`
      - `Context.load_cert_chain()`
      - `Context.load_client_CA()`
      - `Context.load_client_ca()`
      - `Context.load_verify_info()`
      - `Context.load_verify_locations()`
      - `Context.m2_ssl_ctx_free()`
      - `Context.remove_session()`
      - `Context.set_allow_unknown_ca()`
      - `Context.set_cipher_list()`
      - `Context.set_client_CA_list_from_file()`
      - `Context.set_default_verify_paths()`
      - `Context.set_info_callback()`
      - `Context.set_options()`
      - `Context.set_session_cache_mode()`
      - `Context.set_session_id_ctx()`
      - `Context.set_session_timeout()`
      - `Context.set_tmp_dh()`
      - `Context.set_tmp_dh_callback()`
      - `Context.set_tmp_rsa()`
      - `Context.set_tmp_rsa_callback()`
      - `Context.set_verify()`
    - `ctxmap()`
    - `map()`
  - `SSLServer` Module
    - `ForkingSSLServer`
    - `SSLServer`
      - `SSLServer.handle_error()`
      - `SSLServer.handle_request()`
      - `SSLServer.socket`
    - `ThreadingSSLServer`
  - `Session` Module
    - `Session`
      - `Session.as_der()`
      - `Session.as_text()`
      - `Session.get_time()`
      - `Session.get_timeout()`
      - `Session.m2_ssl_session_free()`
      - `Session.set_time()`
      - `Session.set_timeout()`
      - `Session.write_bio()`
    - `load_session()`
  - `TwistedProtocolWrapper` Module
  - `cb` Module
    - `ssl_info_callback()`
    - `ssl_verify_callback()`
    - `ssl_verify_callback_allow_unknown_ca()`
    - `ssl_verify_callback_stub()`
  - `timeout` Module
    - `struct_size()`
    - `struct_to_timeout()`
    - `timeout`
      - `timeout.microsec`
      - `timeout.pack()`
      - `timeout.sec`