nss.nss

This module implements the NSS functions

Functions

algtag_to_mechanism(algtag)
Parameters:
base64_to_binary(text)
Parameters:
cert_crl_reason_from_name crl_reason_from_name(name) -> int
cert_crl_reason_name crl_reason_name(reason) -> string
cert_general_name_type_from_name general_name_type_from_name(name) -> int
cert_general_name_type_name general_name_type_name(type) -> string
cert_type_flags(flags[, repr_kind])
Parameters:
cert_usage_flags(flags[, repr_kind])
Parameters:
clear_ocsp_cache() Removes all items currently stored in the OCSP cache.
create_context_by_sym_key(mechanism, …[, …])
Parameters:
create_digest_context(hash_alg)
Parameters:
create_pbev2_algorithm_id([pbe_alg, …])
Parameters:
data_to_hex(data[, octets_per_line, separator])
Parameters:
decode_der_crl(der_crl[, type, decode_options])
Parameters:
der_universal_secitem_fmt_lines(sec_item[, …])
Parameters:
disable_ocsp_checking([certdb])
Parameters:
disable_ocsp_default_responder([certdb])
Parameters:
dump_certificate_cache_info() Dump the contents of the certificate cache and the temporary cert store to stdout.
enable_ocsp_checking([certdb])
Parameters:
enable_ocsp_default_responder([certdb])
Parameters:
find_cert_from_nickname(nickname, …)
Parameters:
find_certs_from_email_addr(email, …)
Parameters:
find_certs_from_nickname(email, [user_data1, …)
Parameters:
find_key_by_any_cert(cert, [user_data1, …])
Parameters:
find_slot_by_name(name)
Parameters:
fingerprint_format_lines(data[, level])
Parameters:
generate_new_param(mechanism[, sym_key])
Parameters:
generate_random(num_bytes)
Parameters:
get_all_tokens([mechanism, need_rw, …])
Parameters:
get_best_slot(mechanism, [user_data1, …])
Parameters:
get_block_size(mechanism[, sec_param])
Parameters:
get_cert_nicknames(certdb, what, …)
Parameters:
get_default_certdb() Returns the default certificate database as a CertDB object
get_internal_key_slot() Get the default internal key slot.
get_internal_slot() Get the default internal slot.
get_iv_length(mechanism)
Parameters:
get_pad_mechanism(mechanism)
Parameters:
get_use_pkix_for_validation() Returns the current value of the flag used to enable or disable the use of PKIX for certificate validation.
hash_buf hash_buf(hash_alg, data) –> digest
import_crl(slot, der_crl, url, type, …)
Parameters:
import_sym_key(slot, mechanism, origin, …)
Parameters:
indented_format(line_fmt_tuples[, indent_len]) The function supports the display of complex objects which may be composed of other complex objects.
is_fips pk11_is_fips() -> bool
key_mechanism_type_from_name(name)
Parameters:
key_mechanism_type_name(mechanism)
Parameters:
key_usage_flags(flags[, repr_kind])
Parameters:
list_certs(type, [user_data1, …])
Parameters:
make_line_fmt_tuples(level, obj)
Parameters:
md5_digest md5_digest(data) –> digest
mechanism_to_algtag(mechanism)
Parameters:
need_pw_init pk11_need_pw_init() -> bool
nss_get_version() Return a string of the NSS library version
nss_init(cert_dir)
Parameters:
nss_init_context([cert_dir, cert_prefix, …])
Parameters:
nss_init_flags(flags[, repr_kind])
Parameters:
nss_init_nodb() Performs tasks required to run Network Security Services without setting up configuration files.
nss_init_read_write(cert_dir)
Parameters:
nss_initialize([cert_dir, cert_prefix, …])
Parameters:
nss_is_initialized nss_is_initialized() –> bool
nss_shutdown() Closes the key and certificate databases that were opened by nss_init().
nss_shutdown_context(context)
Parameters:
nss_version_check nss_version_check(version) –> bool
oid_dotted_decimal(oid)
Parameters:
oid_str(oid)
Parameters:
oid_tag(oid)
Parameters:
oid_tag_name(oid)
Parameters:
param_from_algid(algid)
Parameters:
param_from_iv(mechanism[, iv])
Parameters:
pk11_attribute_type_from_name(name)
Parameters:
pk11_attribute_type_name(type)
Parameters:
pk11_disabled_reason_name(reason)
Parameters:
pk11_disabled_reason_str(reason)
Parameters:
pk11_logout_all() Logout of every slot for all modules.
pkcs12_cipher_from_name(name)
Parameters:
pkcs12_cipher_name(cipher)
Parameters:
pkcs12_enable_all_ciphers() Enables all PKCS12 ciphers, which are:
pkcs12_enable_cipher(cipher, enabled)
Parameters:
pkcs12_export pkcs12_export(nickname, pkcs12_password, key_cipher=SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC, cert_cipher=SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC, pin_args=None)
pkcs12_map_cipher(cipher[, key_length])
Parameters:
pkcs12_set_nickname_collision_callback(callback)
Parameters:
pkcs12_set_preferred_cipher(cipher, enabled)
Parameters:
pub_wrap_sym_key(mechanism, pub_key, sym_key)
Parameters:
read_der_from_file(file[, ascii])
Parameters:
read_hex(input[, separators])
Parameters:
set_ocsp_cache_settings(max_cache_entries, …)
Parameters:
set_ocsp_default_responder(certdb, url, nickname)
Parameters:
set_ocsp_failure_mode(failure_mode)
Parameters:
set_ocsp_timeout(seconds)
Parameters:
set_password_callback(callback)
Parameters:
set_shutdown_callback(callback, [user_data1, …)
Parameters:
set_use_pkix_for_validation(flag)
Parameters:
sha1_digest sha1_digest(data) –> digest
sha256_digest sha256_digest(data) –> digest
sha512_digest sha512_digest(data) –> digest
token_exists pk11_token_exists(mechanism) -> bool
x509_alt_name(sec_item[, repr_kind])
Parameters:
x509_cert_type(bitstr[, repr_kind])
Parameters:
x509_ext_key_usage(sec_item[, repr_kind])
Parameters:
x509_key_usage(bitstr[, repr_kind])
Parameters:

Classes

AVA An object representing an AVA (attribute value assertion).
AlgorithmID An object representing a signature algorithm
AuthKeyID An object representing Authentication Key ID extension
AuthorityInfoAccess() An object representing AuthorityInfoAccess.
AuthorityInfoAccesses(data)
Parameters:
BasicConstraints An object representing X509 Basic Constraints Extension
CRLDistributionPoint An object representing a CRL Distribution Point
CRLDistributionPts An object representing CRL Distribution Points list
CertAttribute() An object representing CertAttribute.
CertDB An object representing a Certificate Database
CertVerifyLog() An object which collects diagnostic information during certification validation.
CertVerifyLogNode() An object detailing specific diagnostic information concerning a single failure during certification validation.
Certificate(data[, certdb, perm, nickname])
Parameters:
CertificateExtension An object representing a certificate extension
CertificateRequest([data])
Parameters:
DN An object representing an X501 Distinguished Name (e.g DN).
DSAPublicKey A object representing a DSA Public Key
GeneralName An object representing a GeneralName or list of GeneralNames.
InitContext An object representing NSSInitContext
InitParameters An object representing NSS Initialization Parameters
KEYPQGParams([prime, subprime, base])
Parameters:
PK11Context
PK11Slot An object representing a PKCS #11 Slot
PK11SymKey Holds a hash, encryption or signing context for multi-part operations.
PKCS12DecodeItem An object representing an item in a PKCS12 collection.
PKCS12Decoder(file, password[, slot])
Parameters:
PrivateKey An object representing a Private Key
PublicKey An object representing a Public Key
RDN An object representing an X501 Relative Distinguished Name (e.g.
RSAGenParams([key_size, public_exponent])
Parameters:
RSAPublicKey An object representing an RSA Public Key
SecItem([data, type, ascii])
Parameters:
SignedCRL An object representing a signed certificate revocation list
SignedData A object representing a signature
SubjectPublicKeyInfo An object representing a Subject Public Key
class nss.nss.AVA

An object representing an AVA (attribute value assertion).

AVA(type, value)

Parameters:
type : may be one of integer, string, SecItem

What kind of attribute is being created. May be one of:

  • integer: A SEC OID enumeration constant (i.e. SEC_OID_*) for example SEC_OID_AVA_COMMON_NAME.
  • string: A string either as the ava name, for example ‘cn’ or as the dotted decimal representation, for example ‘OID.2.5.4.3’. Case is not significant for either form.
  • SecItem: A SecItem object encapsulating the OID in DER format.
value : string

The value of the AVA, must be a string.

RDN’s (Relative Distinguished Name) are composed from AVA’s. An RDN is a sequence of AVA’s.

An example of an AVA is “CN=www.redhat.com” where CN is the X500 directory abbrevation for “Common Name”.

An AVA is composed of two items:

type
Specifies the attribute (e.g. CN). AVA types are specified by predefined OID’s (Object Identifiers). For example the OID of CN is 2.5.4.3 ({joint-iso-itu-t(2) ds(5) attributeType(4) commonName(3)}) OID’s in NSS are encapsulated in a SecItem as a DER encoded OID. Because DER encoded OID’s are less than ideal mechanisms by which to specify an item NSS has mapped each OID to a integral enumerated constant called an OID tag (i.e. SEC_OID_*). Many of the NSS API’s will accept an OID tag number instead of DER encoded OID in a SecItem. One can easily convert between DER encoded OID’s, tags, and their string representation in dotted-decimal format. The enumerated OID constants are the most efficient in most cases.
value
The value of the attribute (e.g. ‘www.redhat.com’).

Examples:

The AVA cn=www.redhat.com can be created in any of the follow ways:

ava = nss.AVA('cn', 'www.redhat.com')
ava = nss.AVA(nss.SEC_OID_AVA_COMMON_NAME, 'www.redhat.com')
ava = nss.AVA('2.5.4.3', 'www.redhat.com')
ava = nss.AVA('OID.2.5.4.3', 'www.redhat.com')
oid

The OID (e.g. type) of the AVA as a SecItem

oid_tag

The OID tag enumerated constant (i.e. SEC_OID_AVA_*) of the AVA’s type

value

The value of the AVA as a SecItem

value_str

The value of the AVA as a UTF-8 encoded string

class nss.nss.AlgorithmID

An object representing a signature algorithm

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

get_pbe_crypto_mechanism(sym_key, padded=True) -> (mechanism, params)
Parameters:
sym_key : PK11SymKey object

The symmetric key returned from PK11Slot.pbe_key_gen()

padded : bool

Block ciphers require the input data to be a multiple of the cipher block size. The necessary padding can be performed internally, this is controlled by selecting a pad vs. non-pad cipher mechanism. If the padded flag is True the returned mechanism will support padding if possible. If you know you do not need or want a padded mechanism set this flag to False. Selection of a padded mechanism is performed internally by calling nss.get_pad_mechanism().

This function generates the parameters needed for nss.create_context_by_sym_key(), for example:

alg_id = nss.create_pbev2_algorithm_id() sym_key = slot.pbe_key_gen(alg_id, password) mechanism, params = alg_id.get_pbe_crypto_mechanism(sym_key) encrypt_ctx = nss.create_context_by_sym_key(mechanism, nss.CKA_ENCRYPT, sym_key, params)
get_pbe_iv(password) → SecItem
Parameters:
password : string

the password used to create the PBE Key

Returns the IV (Initialization Vector) used for the PBE cipher.

id_oid

algorithm id OID as SecItem

id_str

algorithm id as string description

id_tag

algorithm id TAG as a enumerated constant (e.g. tag)

parameters

algorithm parameters as SecItem

class nss.nss.AuthKeyID

An object representing Authentication Key ID extension

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

get_general_names(repr_kind=AsString) -> (general_name, ...)
Parameters:
repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsObject

The general name as a nss.GeneralName object

AsString

The general name as a string. (e.g. “http://crl.geotrust.com/crls/secureca.crl”)

AsTypeString
The general name type as a string.

(e.g. “URI”)

AsTypeEnum
The general name type as a general name type enumerated constant.

(e.g. nss.certURI )

AsLabeledString

The general name as a string with it’s type prepended. (e.g. “URI: http://crl.geotrust.com/crls/secureca.crl

Returns a tuple of general names in the authentication key id extension for the issuer. If the issuer was not defined then the returned tuple will be empty.

You may specify how the each member of the tuple is represented, by default it will be as a string.

key_id

Returns the key id as a SecItem

serial_number

Returns the key id as a SecItem

class nss.nss.AuthorityInfoAccess

An object representing AuthorityInfoAccess.

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

location

location as a nss.GeneralName object

method_oid

method OID as SecItem

method_str

method as string description

method_tag

method TAG as a enumerated constant (e.g. tag)

class nss.nss.AuthorityInfoAccesses(data)
Parameters:
data : SecItem or str or any buffer compatible object

Data to initialize the Authority Information Access from, must be in DER format

An object representing AuthorityInfoAccess Extension.

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

class nss.nss.BasicConstraints

An object representing X509 Basic Constraints Extension

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

is_ca

returns boolean, True if certificate is a certificate authority (i.e. CA)

path_len

returns max path length constraint as an integer

class nss.nss.CRLDistributionPoint

An object representing a CRL Distribution Point

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

get_general_names(repr_kind=AsString) -> (general_name, ...)
Parameters:
repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsObject

The general name as a nss.GeneralName object

AsString

The general name as a string. (e.g. “http://crl.geotrust.com/crls/secureca.crl”)

AsTypeString
The general name type as a string.

(e.g. “URI”)

AsTypeEnum
The general name type as a general name type enumerated constant.

(e.g. nss.certURI )

AsLabeledString

The general name as a string with it’s type prepended. (e.g. “URI: http://crl.geotrust.com/crls/secureca.crl

Returns a tuple of general names in the CRL Distribution Point. If the distribution point type is not nss.generalName or the list was empty then the returned tuple will be empty.

You may specify how the each member of the tuple is represented, by default it will be as a string.

get_reasons(repr_kind=AsEnumDescription) -> (reason, ...)
Parameters:
repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsEnum

The enumerated constant. (e.g. nss.crlEntryReasonCaCompromise)

AsEnumDescription
A friendly human readable description of the enumerated constant as a string.

(e.g. “CA Compromise”)

AsIndex

The bit position within the bit string.

Returns a tuple of reasons in the CRL Distribution Point. If no reasons were defined the returned tuple will be empty.

You may specify how the each member of the tuple is represented, by default it will be as a string.

issuer

returns the CRL Issuer as a GeneralName object if defined, returns None if not defined

class nss.nss.CRLDistributionPts

An object representing CRL Distribution Points list

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

class nss.nss.CertAttribute

An object representing CertAttribute.

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

type_oid

type OID as SecItem

type_str

type as string description

type_tag

type TAG as a enumerated constant (e.g. tag)

values

tuple of CertificateExtension objects if type_tag == SEC_OID_PKCS9_EXTENSION_REQUEST else tuple of SecItem objects

class nss.nss.CertDB

An object representing a Certificate Database

find_crl_by_cert(cert, type=SEC_CRL_TYPE) → SignedCRL object
Parameters:
cert : Certificate object

certificate used to lookup the CRL.

type : int

revocation list type

may be one of:
  • SEC_CRL_TYPE
  • SEC_KRL_TYPE

Returns a SignedCRL object found in the database given a certificate and revocation list type.

find_crl_by_name(name, type=SEC_CRL_TYPE) → SignedCRL object
Parameters:
name : string

name to lookup

type : int

revocation list type

may be one of:
  • SEC_CRL_TYPE
  • SEC_KRL_TYPE

Returns a SignedCRL object found in the database given a name and revocation list type.

class nss.nss.CertVerifyLog

An object which collects diagnostic information during certification validation.

count

number of validation errors

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

class nss.nss.CertVerifyLogNode

An object detailing specific diagnostic information concerning a single failure during certification validation. These are collected in a CertVerifyLog object.

certificate

returns the certificate as a Certificate object

depth

returns the chain position as an integer

error

returns the error code as an integer

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

class nss.nss.Certificate(data, certdb=get_default_certdb(), perm=False, nickname=None)
Parameters:
data : SecItem or str or any buffer compatible object

Data to initialize the certificate from, must be in DER format

certdb : CertDB object or None

CertDB certificate database object, if None then the default certdb will be supplied by calling nss.get_default_certdb().

perm : bool

True if certificate should be permantely stored in the certdb.

nickname : string

certificate nickname.

An X509 Certificate object.

The Certificate is initialized from the supplied DER data. The Certificate is added to the NSS temporary database. If perm is True then the Certificate is also permanently written into certdb.

cert_type

integer bitmask of NS_CERT_TYPE_* flags, see nss.cert_type_flags()

check_ocsp_status(certdb, time[, user_data1, ...]) → boolean
Parameters:
certdb : CertDB object

CertDB certificate database object.

time : number or None

Time for which status is to be determined. Time as number of microseconds since the NSPR epoch, midnight (00:00:00) 1 January 1970 UTC, either as an integer or a float. If time is None the current time is used.

user_dataN : object

zero or more caller supplied parameters which will be passed to the password callback function

Checks the status of a certificate via OCSP. Will only check status for a certificate that has an AIA (Authority Information Access) extension for OCSP or when a “default responder” is specified and enabled. (If no AIA extension for OCSP and no default responder in place, the cert is considered to have a good status.

Returns True if an approved OCSP responder knows the cert and returns a non-revoked status for it. Otherwise a error.NSPRError is raised and it’s error_code property may be one of the following:

  • SEC_ERROR_OCSP_BAD_HTTP_RESPONSE
  • SEC_ERROR_OCSP_FUTURE_RESPONSE
  • SEC_ERROR_OCSP_MALFORMED_REQUEST
  • SEC_ERROR_OCSP_MALFORMED_RESPONSE
  • SEC_ERROR_OCSP_OLD_RESPONSE
  • SEC_ERROR_OCSP_REQUEST_NEEDS_SIG
  • SEC_ERROR_OCSP_SERVER_ERROR
  • SEC_ERROR_OCSP_TRY_SERVER_LATER
  • SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST
  • SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE
  • SEC_ERROR_OCSP_UNKNOWN_CERT
  • SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS
  • SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE
  • SEC_ERROR_BAD_SIGNATURE
  • SEC_ERROR_CERT_BAD_ACCESS_LOCATION
  • SEC_ERROR_INVALID_TIME
  • SEC_ERROR_REVOKED_CERTIFICATE
  • SEC_ERROR_UNKNOWN_ISSUER
  • SEC_ERROR_UNKNOWN_SIGNER

Other errors are possible failures in cert verification (e.g. SEC_ERROR_REVOKED_CERTIFICATE, SEC_ERROR_UNTRUSTED_ISSUER) when verifying the signer’s cert, or other low-level problems.

check_valid_times()

check_valid_times(time=now, allow_override=False) –> validity

Parameters:
time : number or None

an optional point in time as number of microseconds since the NSPR epoch, midnight (00:00:00) 1 January 1970 UTC, either as an integer or a float. If time is None the current time is used.

allow_override : bool

If True then check to see if the invalidity has been overridden by the user, defaults to False.

Checks whether a specified time is within a certificate’s validity period.

Returns one of:

  • secCertTimeValid
  • secCertTimeExpired
  • secCertTimeNotValidYet
der_data

raw certificate DER data as data buffer

email_trust_flags

certificate email trust flags as integer bitmask, or None if not defined

email_trust_str

certificate email trust flags as array of strings, or None if trust is not defined

extensions

certificate extensions as a tuple of CertificateExtension objects

find_kea_type() → kea_type

Returns key exchange type of the keys in an SSL server certificate.

May be one of the following:
  • ssl_kea_null
  • ssl_kea_rsa
  • ssl_kea_dh
  • ssl_kea_fortezza (deprecated)
  • ssl_kea_ecdh
format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

get_cert_chain(time=now, usages=certUsageAnyCA) -> (`Certificate`, ...)
Parameters:
time : number or None

an optional point in time as number of microseconds since the NSPR epoch, midnight (00:00:00) 1 January 1970 UTC, either as an integer or a float. If time is None the current time is used.

usages : integer

a certUsage* enumerated constant

Returns a tuple of Certificate objects.

get_extension(oid) → `CertificateExtension`

Given an oid identifying the extension try to locate it in the certificate and return it as generic CertificateExtension object. If the extension is not present raise a KeyError.

The generic CertificateExtension object is not terribly useful on it’s own, howerver it’s value property can be used to intialize instances of a class representing the extension. Or it may be passed to functions that convert the value into some other usable format. Although one might believe this function should do these conversions for you automatically there are too many possible variations. Plus one might simple be interested to know if an extension is present or not. So why perform conversion work that might not be needed or might not be in the format needed? Therefore this function is just one simple element in a larger toolbox. Below are some suggestions on how to convert the generic CertificateExtension object (this list may not be complete).

SEC_OID_PKCS12_KEY_USAGE
x509_key_usage()
SEC_OID_X509_SUBJECT_KEY_ID
SecItem.der_to_hex()
SEC_OID_X509_CRL_DIST_POINTS
CRLDistributionPts()
case SEC_OID_X509_AUTH_KEY_ID
AuthKeyID()
SEC_OID_X509_EXT_KEY_USAGE
x509_ext_key_usage()
SEC_OID_X509_BASIC_CONSTRAINTS
BasicConstraints()
SEC_OID_X509_SUBJECT_ALT_NAME
x509_alt_name()
SEC_OID_X509_ISSUER_ALT_NAME
x509_alt_name()
Parameters:
oid : may be one of integer, string, SecItem

The OID of the certification extension to retreive May be one of:

  • integer: A SEC OID enumeration constant (i.e. SEC_OID_*) for example SEC_OID_X509_BASIC_CONSTRAINTS.
  • string: A string either the OID name, with or without the SEC_OID_ prefix (e.g. “SEC_OID_X509_BASIC_CONSTRAINTS” or “X509_BASIC_CONSTRAINTS”) or as the dotted decimal representation, for example ‘OID.2 5 29 19’. Case is not significant for either form.
  • SecItem: A SecItem object encapsulating the OID in DER format.
Returns:

generic CertificateExtension object

has_signer_in_ca_names(ca_names) → bool
Parameters:
ca_names : (SecItem, …)

Sequence of CA distinguished names. Each item in the sequence must be a SecItem object containing a distinguished name.

Returns True if any of the signers in the certificate chain for a specified certificate are in the list of CA names, False otherwise.

is_ca_cert(return_cert_type=False) → boolean

is_ca_cert(True) -> boolean, cert_type

Parameters:
return_cert_type : boolean

If True returns both boolean result and certficate type bitmask. If False return only boolean result

Returns True if the cert is a CA cert, False otherwise.

The function optionally can return a bitmask of NS_CERT_TYPE_* flags if return_cert_type is True. This is the updated cert type after applying logic in the context of deciding if the cert is a CA cert or not. Hint: the cert_type value can be converted to text with nss.cert_type_flags(). Hint: the unmodified cert type flags can be obtained with the Certificate.cert_type property.

issuer

certificate issuer as a DN object

make_ca_nickname() → string

Returns a nickname for the certificate guaranteed to be unique within the the current NSS database.

The nickname is composed thusly:

  1. Establish a name by trying in order:
    1. subject’s common name (i.e. CN)
    2. subject’s organizational unit name (i.e. OU)
  2. Establish a realm by trying in order:
    1. issuer’s organization name (i.e. O)
    2. issuer’s distinguished name (i.e. DN)
    3. set to “Unknown CA”
  3. If name exists the nickname will be “name - realm”, else the nickname will be “realm”
  4. Then the nickname will be tested for existence in the database. If it does not exist it will be returned as the nickname. Else a loop is entered where the nickname will have ” #%d” appended to it where %d is an integer beginning at 1. The generated nickname is tested for existence in the dabase until a unique name is found.
serial_number

certificate serial number

set_trust_attributes(trust, certdb, slot[, user_data1, ...])
Parameters:
string : trust

NSS trust string

certdb : CertDB object or None

CertDB certificate database object, if None then the default certdb will be supplied by calling nss.get_default_certdb().

slot : PK11Slot object

The PK11 slot to use. If None defaults to internal slot, see nss.get_internal_key_slot()

user_dataN : object

zero or more caller supplied parameters which will be passed to the password callback function

signature_algorithm

certificate signature algorithm

signed_data

certificate signature as SignedData object

signing_trust_flags

certificate object signing trust flags as integer bitmask, or None if not defined

signing_trust_str

certificate object signing trust flags as array of strings, or None if trust is not defined

ssl_trust_flags

certificate SSL trust flags as integer bitmask, or None if not defined

ssl_trust_str

certificate SSL trust flags as array of strings, or None if trust is not defined

subject

certificate subject as a DN object

subject_common_name

certificate subject

subject_public_key_info

certificate public info as SubjectPublicKeyInfo object

trust_flags(flags, repr_kind=AsEnumDescription) → ['flag_name', ...]
Parameters:
flags : int

certificate trust integer bitmask

repr_kind : RepresentationKind constant

Specifies what the contents of the returned list will be. May be one of:

AsEnum

The enumerated constant as an integer value.

AsEnumName

The name of the enumerated constant as a string.

AsEnumDescription

A friendly human readable description of the enumerated constant as a string.

Given an integer with trust flags encoded as a bitmask return a sorted list of their values as specified in the repr_kind

This is a class method.

valid_not_after

certificate not valid after this time (floating point value expressed as microseconds since the epoch, midnight January 1st 1970, UTC)

valid_not_after_str

certificate not valid after this time (string value expressed, UTC)

valid_not_before

certificate not valid before this time (floating point value expressed as microseconds since the epoch, midnight January 1st 1970 UTC)

valid_not_before_str

certificate not valid before this time (string value expressed, UTC)

verify(certdb, check_sig, required_usages, time[, user_data1, ...]) → valid_usages
Parameters:
certdb : CertDB object

CertDB certificate database object

check_sig : bool

True if certificate signatures should be checked

required_usages : integer

A bitfield of all cert usages that are required for verification to succeed. If zero return all possible valid usages.

time : number or None

an optional point in time as number of microseconds since the NSPR epoch, midnight (00:00:00) 1 January 1970 UTC, either as an integer or a float. If time is None the current time is used.

user_dataN : object

zero or more caller supplied parameters which will be passed to the password callback function

Verify a certificate by checking if it’s valid and that we trust the issuer.

Possible usage bitfield values are:
  • certificateUsageCheckAllUsages
  • certificateUsageSSLClient
  • certificateUsageSSLServer
  • certificateUsageSSLServerWithStepUp
  • certificateUsageSSLCA
  • certificateUsageEmailSigner
  • certificateUsageEmailRecipient
  • certificateUsageObjectSigner
  • certificateUsageUserCertImport
  • certificateUsageVerifyCA
  • certificateUsageProtectedObjectSigner
  • certificateUsageStatusResponder
  • certificateUsageAnyCA

Returns valid_usages, a bitfield of certificate usages.

If required_usages is non-zero, the returned bitmap is only for those required usages, otherwise it is for all possible usages.

Hint: You can obtain a printable representation of the usage flags via cert_usage_flags.

Note: Anytime a NSPR or NSS function returns an error in python-nss it raises a NSPRError exception. When an exception is raised the normal return values are discarded because the flow of control continues at the first except block prepared to catch the exception. Normally this is what is desired because the return values would be invalid due to the error. However the certificate verification functions are an exception (no pun intended). An error might be returned indicating the cert failed verification but you may still need access to the returned usage bitmask and the log (if using the log variant). To handle this a special error exception CertVerifyError (derived from NSPRError) is defined which in addition to the normal NSPRError fields will also contain the returned usages and optionally the CertVerifyLog object. If no exception is raised these are returned as normal return values.

verify_hostname(hostname) → bool

A restricted regular expression syntax is used to test if the common name specified in the subject DN of the certificate is a match, returning True if so, False otherwise.

The regular expression systax is:
*
matches anything
?
matches one character
\ (backslash)
escapes a special character
$
matches the end of the string
[abc]
matches one occurrence of a, b, or c. The only character that needs to be escaped in this is ], all others are not special.
[a-z]
matches any character between a and z
[^az]
matches any character except a or z
~
followed by another shell expression removes any pattern matching the shell expression from the match list
(foo|bar)
matches either the substring foo or the substring bar. These can be shell expressions as well.
verify_now(certdb, check_sig, required_usages[, user_data1, ...]) → valid_usages
Parameters:
certdb : CertDB object

CertDB certificate database object

check_sig : bool

True if certificate signatures should be checked

required_usages : integer

A bitfield of all cert usages that are required for verification to succeed. If zero return all possible valid usages.

user_dataN : object

zero or more caller supplied parameters which will be passed to the password callback function

Verify a certificate by checking if it’s valid and that we trust the issuer.

Possible usage bitfield values are:
  • certificateUsageCheckAllUsages
  • certificateUsageSSLClient
  • certificateUsageSSLServer
  • certificateUsageSSLServerWithStepUp
  • certificateUsageSSLCA
  • certificateUsageEmailSigner
  • certificateUsageEmailRecipient
  • certificateUsageObjectSigner
  • certificateUsageUserCertImport
  • certificateUsageVerifyCA
  • certificateUsageProtectedObjectSigner
  • certificateUsageStatusResponder
  • certificateUsageAnyCA

Returns valid_usages, a bitfield of certificate usages. If required_usages is non-zero, the returned bitmap is only for those required usages, otherwise it is for all possible usages.

Hint: You can obtain a printable representation of the usage flags via cert_usage_flags.

Note: See the Certificate.verify documentation for details on how the Certificate verification functions handle errors.

verify_with_log(certdb, check_sig, required_usages, time[, user_data1, ...]) → valid_usages, log
Parameters:
certdb : CertDB object

CertDB certificate database object

check_sig : bool

True if certificate signatures should be checked

required_usages : integer

A bitfield of all cert usages that are required for verification to succeed. If zero return all possible valid usages.

time : number or None

an optional point in time as number of microseconds since the NSPR epoch, midnight (00:00:00) 1 January 1970 UTC, either as an integer or a float. If time is None the current time is used.

user_dataN : object

zero or more caller supplied parameters which will be passed to the password callback function

Verify a certificate by checking if it’s valid and that we trust the issuer.

Possible usage bitfield values are:
  • certificateUsageCheckAllUsages
  • certificateUsageSSLClient
  • certificateUsageSSLServer
  • certificateUsageSSLServerWithStepUp
  • certificateUsageSSLCA
  • certificateUsageEmailSigner
  • certificateUsageEmailRecipient
  • certificateUsageObjectSigner
  • certificateUsageUserCertImport
  • certificateUsageVerifyCA
  • certificateUsageProtectedObjectSigner
  • certificateUsageStatusResponder
  • certificateUsageAnyCA

Returns valid_usages, a bitfield of certificate usages and a nss.CertVerifyLog object with diagnostic information detailing the reasons for a validation failure.

If required_usages is non-zero, the returned bitmap is only for those required usages, otherwise it is for all possible usages.

Hint: You can obtain a printable representation of the usage flags via cert_usage_flags.

Note: See the Certificate.verify documentation for details on how the Certificate verification functions handle errors.

version

certificate version

class nss.nss.CertificateExtension

An object representing a certificate extension

critical

extension is critical flag (boolean)

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

name

name of extension

oid

oid of extension as SecItem

oid_tag

oid of extension as a enumerated constant (e.g. tag)

value

extension data as SecItem

class nss.nss.CertificateRequest(data=None)
Parameters:
data : SecItem or str or any buffer compatible object

Data to initialize the certificate request from, must be in DER format

An object representing a certificate request

attributes

certificate request attributes as a tuple of CertAttribute objects

extensions

certificate extensions as a tuple of CertificateExtension objects

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

subject

subject as an DN object

subject_public_key_info

certificate public info as SubjectPublicKeyInfo object

version

version as integer

class nss.nss.DN

An object representing an X501 Distinguished Name (e.g DN).

DN objects contain an ordered list of RDN objects.

The DN object constructor may be invoked with a string representing an X500 name. Zero or more RDN objects, or you may optionally pass a list or tuple of RDN objects.

Examples:

DN()
DN('CN=www.redhat.com,OU=Web Operations,O=Red Hat Inc,L=Raleigh,ST=North Carolina,C=US')
DN(rdn0, ...)
DN([rdn0, rdn1])

The string representation of a Distinguished Name (DN) has reverse ordering from it’s sequential components.

The ordering is a requirement of the relevant RFC’s. When a Distinguished Name is rendered as a string it is ordered from most specific to least specific. However it’s components (RDN’s) as a sequence are ordered from least specific to most specific.

DN objects contain an ordered list of RDN objects. The DN object has both sequence and mapping behaviors with respect to the RDN’s they contain. Thus you can index an RDN by position, by name, or by SecItem (if it’s an OID). You can iterate over the list, get it’s length or take a slice.

If you index by string the string may be either a canonical name for the RDN type (e.g. ‘cn’) or the dotted-decimal notation for the OID (e.g. 2.5.4.3). There may be multiple RDN’s in a DN whose type matches (e.g. OU=engineering, OU=boston). It is not common to have more than one RDN in a DN with the same type. However because of the possiblity of being multi-valued when indexing by type a list is always returned containing the matching RDN’s. Thus:

dn = nss.DN('OU=engineering')
dn['ou']
    returns [RDN('OU=engineering')

dn = nss.DN('OU=engineering, OU=boston')
dn['ou']
    returns [RDN('OU=boston'), RDN('OU=engineering')]
    Note the reverse ordering between string representation and RDN sequencing

Note, if you use properties to access the RDN values (e.g. name.common_name, name.org_unit_name) the string value is returned or None if not found. If the item was multi-valued then the most appropriate item will be selected and returned as a string value.

Note it is not possible to index by oid tag (e.g. nss.SEC_OID_AVA_COMMON_NAME) because oid tags are integers and it’s impossible to distinguish between an integer representing the n’th member of the sequence and the integer representing the oid tag. In this case positional indexing wins (e.g. rdn[0] means the first element).

Examples:

subject_name = 'CN=www.redhat.com,OU=Web Operations,O=Red Hat Inc,L=Raleigh,ST=North Carolina,C=US'
name = nss.DN(subject_name)
str(name)
   returns 'CN=www.redhat.com,OU=Web Operations,O=Red Hat Inc,L=Raleigh,ST=North Carolina,C=US'
name[0]
   returns an `RDN` object with the value C=US
name['cn']
    returns a list comprised of an `RDN` object with the value CN=www.redhat.com
name['2.5.4.3']
    returns a list comprised of an `RDN` object with the value CN=www.redhat.com
    because 2.5.4.3 is the dotted-decimal OID for common name (i.e. cn)
name.common_name
    returns the string www.redhat.com
    common_name is easy shorthand property, it only retuns a single string
    value or None, if it was multi-valued the most appropriate item is selected.
name.has_key('cn')
    returns True because the DN has a common name RDN
name.has_key('2.5.4.3')
    returns True because the DN has a common name RDN
    because 2.5.4.3 is the dotted-decimal OID for common name (i.e. cn)

cn_rdn = nss.RDN(nss.AVA('cn', 'www.redhat.com'))
ou_rdn = nss.RDN(nss.AVA('ou', 'Web Operations'))
name = nss.DN(cn_rdn)
name
   is a DN with one RDN (e.g. CN=www.redhat.com)
len(name)
   returns 1 because there is one RDN in it
name.add_rdn(ou_rdn)
name
   name is now a DN with two RDN's (e.g. OU=Web Operations,CN=www.redhat.com)
len(name)
   returns 2 because there are now two RDN's in it
list(name)
   returns a list with the two RDN's in it
name[:]
   same as list(name)
for rdn in name:
   iterate over each RDN in name
name = nss.DN(cn_rdn, ou_rdn)
    This is an alternate way to build the above DN
add_rdn()

add_rdn(rdn)

Parameters:
rdn : RDN object

The rnd to add to the name

Adds a RDN to the name.

cert_uid

Returns the certificate uid member (i.e. UID) as a string. Returns None if not found.

common_name

Returns the common name member (i.e. CN) as a string. Returns None if not found.

country_name

Returns the country name member (i.e. C) as a string. Returns None if not found.

dc_name

Returns the domain component name member (i.e. DC) as a string. Returns None if not found.

email_address

Returns the email address member as a string. Returns None if not found.

has_key(arg) → bool
Parameters:
arg : string or integer

canonical name (e.g. ‘cn’) or oid dotted-decimal or SEC_OID_* enumeration constant

return True if Name has an AVA whose oid can be identified by arg.

locality_name

Returns the locality name member (i.e. L) as a string. Returns None if not found.

org_name

Returns the organization name member (i.e. O) as a string. Returns None if not found.

org_unit_name

Returns the organizational unit name member (i.e. OU) as a string. Returns None if not found.

state_name

Returns the state name member (i.e. ST) as a string. Returns None if not found.

class nss.nss.DSAPublicKey

A object representing a DSA Public Key

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

pqg_params

DSA P,Q,G params as a KEYPQGParams object

public_value

DSA public_value

class nss.nss.GeneralName

An object representing a GeneralName or list of GeneralNames.

get_name(repr_kind=AsString)
Parameters:
repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsObject

The general name as a nss.GeneralName object

AsString

The general name as a string. (e.g. “http://crl.geotrust.com/crls/secureca.crl”)

AsTypeString
The general name type as a string.

(e.g. “URI”)

AsTypeEnum
The general name type as a general name type enumerated constant.

(e.g. nss.certURI )

AsLabeledString

The general name as a string with it’s type prepended. (e.g. “URI: http://crl.geotrust.com/crls/secureca.crl

Returns the value of the GeneralName according to the representation type parameter.

name

Returns the general name as a string

type_enum

Returns the general name type enumerated constant

type_name

Returns the general name type enumerated constant as a string

type_string

Returns the type of the general name as a string (e.g. “URI”)

class nss.nss.InitContext

An object representing NSSInitContext

shutdown()

Shutdown NSS for this context.

class nss.nss.InitParameters

An object representing NSS Initialization Parameters

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

manufacturer_id

manufacturer id (max 32 chars)

min_password_len

minimum password length

password_required

boolean indicating if a password is required

class nss.nss.KEYPQGParams(prime=None, subprime=None, base=None)
Parameters:
prime : SecItem or str or any buffer compatible object or None

prime (also known as p)

subprime : SecItem or str or any buffer compatible object or None

subprime (also known as q)

base : SecItem or str or any buffer compatible object or None

base (also known as g)

An object representing DSA key parameters
  • prime (also known as p)
  • subprime (also known as q)
  • base (also known as g)

If no parameters are passed the default PQG the KeyPQGParams will be intialized to default values. If you pass any initialization parameters then they must all be passed.

base

key base value, also known as g

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

prime

key prime value, also known as p

subprime

key subprime value, also known as q

class nss.nss.PK11Context
cipher_op(data) → data
Parameters:
data : any read buffer compatible object (e.g. buffer or string)

raw data to compute digest from

Execute a digest/signature operation.

clone_context(context) → PK11Context
Parameters:
context : PK11Context object

The PK11Context to be cloned

Create a new PK11Context which is clone of the supplied context.

digest_begin()

Start a new digesting or Mac’ing operation on this context.

digest_final() → data

Completes the multi-part cryptographic operation in progress on this context and returns any final data which may have been pending in the context (i.e. the output data is flushed from the context). If there was no final data the returned data buffer will have a length of zero.

digest_key(sym_key)
Parameters:
sym_key : PK11SymKey object

symmetric key

Continues a multiple-part message-digesting operation by digesting the value of a secret key.

digest_op(data)
Parameters:
data : any read buffer compatible object (e.g. buffer or string)

raw data to compute digest from

Execute a digest/signature operation.

finalize()

Clean up cipher operation so that any pending multi-part operations have been flushed. Any pending output which would have been available as a result of the flush is discarded. The context is left in a state available for reuse.

WARNING: Currently context reuse only works for digest contexts not encryption/decryption contexts

class nss.nss.PK11Slot

An object representing a PKCS #11 Slot

authenticate(load_certs=False[, user_data1, ...])
Parameters:
load_certs : bool

If True load certificates after authenticating.

Checks to see if token needs to be logged in. If so it invokes the password callback (set via nss.set_password_callback()) passing the optional user_data parameters to the password callback.

change_passwd(old_passwd=None, new_passwd=None)

Change the user password on the token.

Parameters:
old_passwd : string or None

Previouis password.

new_passwd : string or None

New password.

check_security_officer_passwd(security_officer_passwd) → bool

Verify security officer password.

Parameters:
security_officer_passwd : string

Security Officer password.

check_user_passwd(user_passwd)

Verify security officer password.

Parameters:
user_passwd : string

user password.

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

generate_key_pair(mechanism, key_params, token, sensitive[, user_data1, ...]) → public_key, private_key
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

key_params : SecItem object or None

SecItem key parameters. None is also valid.

token : bool

If true the key is a token object otherwise it’s a session object.

sensitive : bool

If a key is sensitive, certain attributes of the key cannot be revealed in plaintext outside the token. It is also more expensive to move between tokens.

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Generate a public and private key pair.

Example:

# Generate a DSA key pair
key_params = nss.KEYPQGParams()
mechanism = nss.CKM_DSA_KEY_PAIR_GEN
slot = nss.get_best_slot(mechanism)
pub_key, priv_key = slot.generate_key_pair(mechanism, key_params, False, False)

# Generate a DSA key pair
key_params = nss.RSAGenParams()
mechanism = nss.CKM_RSA_PKCS_KEY_PAIR_GEN
slot = nss.get_best_slot(mechanism)
pub_key, priv_key = slot.generate_key_pair(mechanism, key_params, False, False)
get_best_key_length(mechanism) → length
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

Return the best key length for this slot and mechanism. A zero result means that token knows how long the key should be, the result is typically used with key_gen(), token_key_gen(), or token_key_gen_with_flags()

get_best_wrap_mechanism() → mechanism

Find the best key wrap mechanism for this slot.

get_disabled_reason() → integer

Returns a diabled reason enumerated constant (i.e. PK11_DIS_*).

May be one of:

  • PK11_DIS_NONE
  • PK11_DIS_USER_SELECTED
  • PK11_DIS_COULD_NOT_INIT_TOKEN
  • PK11_DIS_TOKEN_VERIFY_FAILED
  • PK11_DIS_TOKEN_NOT_PRESENT
has_protected_authentication_path() → bool

Returns True if token has a “protected authentication path”, whereby a user can log into the token without passing a PIN through the library, False otherwise. An example might be a token with an integrated key pad.

has_root_certs() → bool

Returns True if the slot contains the root certificate , False otherwise.

init_pin(security_officer_passwd=None, user_passwd=None)

Initialize the token’s pin for first use.

Parameters:
security_officer_passwd : string or None

Security Officer password used to unlock token.

user_passwd : string or None

User password to set as token pin.

is_disabled() → bool

Returns True if the slot is disabled, False otherwise.

is_friendly() → bool

Returns True if the slot allows certificates to be read without logging in to the token, False otherwise.

is_hw() → bool

Returns True if the slot is implemented in hardware, False otherwise.

is_internal() → bool

Returns True if the the slot is internal, False otherwise.

is_logged_in([user_data1, ...]) → bool
Parameters:
user_data1 : object …

zero or more caller supplied parameters which will be passed to the password callback function

Return True if token is logged in, False otherwise.

is_present() → bool

Returns True if the slot’s token present, False otherwise.

is_read_only() → bool

Returns True if the the slot is read-only, False otherwise.

is_removable() → bool

Returns True if the token is removable, False otherwise.

key_gen(mechanism, sec_param, key_size[, user_data1, ...]) → PK11SymKey object
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

sec_param : SecItem object or None

SecItem key parameters. None is also valid.

key_size : int

key length (use get_best_key_length())

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Generate a symmetric key.

list_certs() -> (`Certificate`, ...)

Returns a tuple of Certificate objects found in the slot.

logout()

logout()l

Logs a user out of a session destroying any objects allocated on their behalf.

need_login() → bool

Returns True if there are some cryptographic functions that a user must be logged in to perform, False otherwise.

need_user_init() → bool

Returns True if the slot needs to be logged into by the user by providing their pin, False otherwise.

pbe_key_gen(algid, password[, user_data1, ...]) → PK11SymKey object
Parameters:
algid : AlgorithmID object

algorithm id

password : string

the password used to create the PBE Key

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Generate a PBE symmetric key.

slot_name

slot name

token_name

token name

user_disable()

user_disable()

Prevents the slot from being used, and sets disable reason to PK11_DIS_USER_SELECTED.

Mechanisms that were on continue to stay on. Therefore, when the slot is enabled again via PK11Slot.user_enable(), it will remember what mechanisms needs to be turned on.

user_enable()

user_enable()

Allow all mechanisms that are ON before PK11Slot.user_disable() was called to be available again. Sets disable reason to PK11_DIS_NONE.

class nss.nss.PK11SymKey

Holds a hash, encryption or signing context for multi-part operations.

derive(mechanism, sec_param, target, operation, key_size) → PK11SymKey
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

sec_param : SecItem object or None

mechanism parameters or None.

target : int

key mechanism enumeration constant (CKM_*)

operation : int

type of operation. A (CKA_*) constant (e.g. CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, CKA_DIGEST)

key_size : int

key size.

Derive a new key from this key. Return a key which can do exactly one operation, it is ephemeral (session key).

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

key_data

key data

key_length

key length

mechanism

CK_MECHANISM_TYPE mechanism

slot
unwrap_sym_key(mechanism, sec_param, wrapped_key, target, operation, key_size) → PK11SymKey
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

sec_param : SecItem object or None

mechanism parameters or None.

wrapped_key : SecItem object

the symmetric key to unwrap

target : int

key mechanism enumeration constant (CKM_*)

operation : int

type of operation. A (CKA_*) constant (e.g. CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, CKA_DIGEST)

key_size : int

key size.

Unwrap (decrypt) the supplied wrapped key. Return the unwrapped key as a PK11SymKey.

wrap_sym_key(mechanism, sec_param, sym_key) → SecItem
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

sec_param : SecItem object or None

mechanism parameters or None.

sym_key : PK11SymKey object

the symmetric key to wrap

Wrap (encrypt) the supplied sym_key using the mechanism and parameter. Return the wrapped key as a SecItem.

class nss.nss.PKCS12DecodeItem

An object representing an item in a PKCS12 collection. Also known as a “bag”

certificate

certificate as Certificate object, or None if does not exist

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

friendly_name

friendly_name as unicode object, or None if does not exist

has_key

boolean indicating if this is a cert with a private key

shroud_algorithm_id

shroud algorithm id certificate as AlgorithmID object, or None if does not exist

signed_cert_der

signed certificate DER data as SecItem object, or None if does not exist

type

SEC OID tag indicating what type of PKCS12 item this is

class nss.nss.PKCS12Decoder(file, password, slot=None)
Parameters:
file : file name or file object

pkcs12 input data.

  • If string treat as file path to open and read.
  • If file object read from the file object.
password : string

The password protecting the PKCS12 contents

slot : PK11Slot object

The PK11 slot to use. If None defaults to internal slot, see nss.get_internal_key_slot()

database_import()

import()

Import the contents of the PKCS12Decoder object into the current NSS database.

During import if the certificate(s) in the PKCS12Decoder object does not have a nickname or there is a collision with an existing nickname then a callback will be invoked to provide a new nickname. See pkcs12_set_nickname_collision_callback.

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

class nss.nss.PrivateKey

An object representing a Private Key

class nss.nss.PublicKey

An object representing a Public Key

dsa

RSA key as a RSAPublicKey object

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

key_type

key type (e.g. rsaKey, dsaKey, etc.) as an int

key_type_str

key type as a string

rsa

RSA key as a RSAPublicKey object

class nss.nss.RDN

An object representing an X501 Relative Distinguished Name (e.g. RDN).

RDN objects contain an ordered list of AVA objects.

Examples:

RDN()
RDN(nss.AVA('cn', 'www.redhat.com'))
RDN([ava0, ava1])

The RDN object constructor may be invoked with zero or more AVA objects, or you may optionally pass a list or tuple of AVA objects.

RDN objects contain an ordered list of AVA objects. The RDN object has both sequence and mapping behaviors with respect to the AVA’s they contain. Thus you can index an AVA by position, by name, or by SecItem (if it’s an OID). You can iterate over the list, get it’s length or take a slice.

If you index by string the string may be either a canonical name for the AVA type (e.g. ‘cn’) or the dotted-decimal notation for the OID (e.g. 2.5.4.3). There may be multiple AVA’s in a RDN whose type matches (e.g. OU=engineering+OU=boston). It is not common to have more than one AVA in a RDN with the same type. However because of the possiblity of being multi-valued when indexing by type a list is always returned containing the matching AVA’s. Thus:

rdn = nss.RDN(nss.AVA('OU', 'engineering'))
rdn['ou']
    returns [AVA('OU=engineering')

rdn = nss.RDN(nss.AVA('OU', 'engineering'), nss.AVA('OU', 'boston'))
rdn['ou']
    returns [AVA('OU=boston'), AVA('OU=engineering')]

Examples:

rdn = nss.RDN(nss.AVA('cn', 'www.redhat.com'))
str(rdn)
   returns 'CN=www.redhat.com'
rdn[0]
   returns an `AVA` object with the value C=US
rdn['cn']
    returns a list comprised of an `AVA` object with the value CN=www.redhat.com
rdn['2.5.4.3']
    returns a list comprised of an `AVA` object with the value CN=www.redhat.com
    because 2.5.4.3 is the dotted-decimal OID for common name (i.e. cn)
rdn.has_key('cn')
    returns True because the RDN has a common name RDN
rdn.has_key('2.5.4.3')
    returns True because the RDN has a common name AVA
    because 2.5.4.3 is the dotted-decimal OID for common name (i.e. cn)
len(rdn)
   returns 1 because there is one `AVA` object in it
list(rdn)
   returns a list of each `AVA` object in it
has_key(arg) → bool
Parameters:
arg : string or integer

canonical name (e.g. ‘cn’) or oid dotted-decimal or SEC_OID_* enumeration constant

return True if RDN has an AVA whose oid can be identified by arg.

class nss.nss.RSAGenParams(key_size=1024, public_exponent=0x10001)
Parameters:
key_size : integer

RSA key size in bits.

public_exponent : integer

public exponent.

An object representing RSAGenParams.

key_size

key size in bits (integer)

public_exponent

public exponent (integer)

class nss.nss.RSAPublicKey

An object representing an RSA Public Key

exponent

RSA exponent

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

modulus

RSA modulus

class nss.nss.SecItem(data=None, type=siBuffer, ascii=False)
Parameters:
data : any read buffer compatible object (e.g. buffer or string)

raw data to initialize from

type : int

SECItemType constant (e.g. si*)

ascii : bool

If true then data is interpretted as base64 encoded. A PEM header and footer is permissible, if present the base64 data will be found inside the PEM delimiters.

A SecItem is a block of binary data. It contains the data, a count of the number of octets in the data and optionally a type describing the contents of the data. SecItem’s are used throughout NSS to pass blocks of binary data back and forth. Because the binary data is often DER (Distinguished Encoding Rule) ASN.1 data the data is often referred to as ‘der’.

SecItem’s are often returned by NSS functions.

You can create and initialize a SecItem yourself by passing the data to the SecItem constructor. If you do initialize the data you may either pass binary data or text (when ascii == True). When you pass ascii data it will be interpreted as base64 encoded binary data. The base64 text may optionally be wrapped inside PEM delimiters, but PEM format is not required.

data

contents of SecItem buffer

der_to_hex(octets_per_line=0, separator=':') → string or list of strings
Parameters:
octets_per_line : integer

Number of octets formatted on one line, if 0 then return a single string instead of an array of lines

separator : string

String used to seperate each octet If None it will be as if the empty string had been passed and no separator will be used.

Interpret the SecItem as containing DER encoded data consisting of a <type,length,value> triplet (e.g. TLV). This function skips the type and length components and returns the value component as a hexadecimal string or a list of hexidecimal strings with a maximum of octets_per_line in each list element. See data_to_hex() for a more detailed explanation.

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

get_integer() → int or long

If the SecItem contains an ASN.1 integer in DER format return a Python integer (or long)

get_oid_sequence(repr_kind=AsString) -> (obj, ...)
Parameters:
repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsObject

Each extended key usage will be a SecItem object embedding the OID in DER format.

AsString

Each extended key usage will be a descriptive string. (e.g. “TLS Web Server Authentication Certificate”)

AsDottedDecimal

Each extended key usage will be OID rendered as a dotted decimal string. (e.g. “OID.1.3.6.1.5.5.7.3.1”)

AsEnum

Each extended key usage will be OID tag enumeration constant (int). (e.g. nss.SEC_OID_EXT_KEY_USAGE_SERVER_AUTH)

Return a tuple of OID’s according the representation kind.

len

number of octets in SecItem buffer

to_base64(chars_per_line=64, pem_type=) → string or list of strings
Parameters:
chars_per_line : integer

Number of characters formatted on one line, if 0 then return a single string instead of an array of lines

pem_type : string

If supplied the base64 encoded data will be wrapped with a PEM header and footer whose type is the string.

Format the binary data in the SecItem as base64 string(s). Either a list of strings is returned or a single string.

If chars_per_line is greater than zero then a list of strings will be returned where each string contains chars_per_line number of characters (except for the last string in the list which will contain the remainder of the characters). Returning a list of “lines” makes it convenient for a caller to format a block of base64 data with line wrapping. If chars_per_line is greater than zero indicating a list result is desired a list is always returned even if the number of characters would produce only a single line.

If chars_per_line is zero then a single string is returned, (no line splitting is performed).

Examples:

If data is:

c8:94:00:9f:c2:8d:a2:5a:61:92:f2:cd:39:75:73:f4

data.to_hex(0) will return the single string:

'yJQAn8KNolphkvLNOXVz9A=='

data.to_hex(5) will return a list of strings where each string has a length of 5 (except the last string which may be shorter):

[
     'yJQAn',
     '8KNol',
     'phkvL',
     'NOXVz',
     '9A=='
]

If you specify the pem_type optional parameter the return value will be a list of strings whose first and last strings will be a PEM header and footer. For example if pem_type=’CERTIFICATE’ then the return value will be like this:

[
    '-----BEGIN CERTIFICATE-----',
    'yJQAn8KNolphkvLNOXVz9A=='
    '-----END CERTIFICATE-----'
]

When a list of strings is returned it is easy to form a single text block using the line ending of your choice, for example:

'\n'.join(data.to_base64())

Thus a PEM block can be formed like this:

'\n'.join(data.to_base64(pem_type='CERTIFICATE'))
to_hex(octets_per_line=0, separator=':') → string or list of strings
Parameters:
octets_per_line : integer

Number of octets formatted on one line, if 0 then return a single string instead of an array of lines

separator : string

String used to seperate each octet If None it will be as if the empty string had been passed and no separator will be used.

Equivalent to calling data_to_hex(sec_item)

type

the SecItem type (si* constant)

class nss.nss.SignedCRL

An object representing a signed certificate revocation list

delete_permanently()

Permanently remove the CRL from the database.

class nss.nss.SignedData

A object representing a signature

algorithm

signature algorithm as a AlgorithmID object

data

signed data as a SecItem object

der

original der encoded ASN1 signed data as a SecItem object

format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

signature

signature as a SecItem object

class nss.nss.SubjectPublicKeyInfo

An object representing a Subject Public Key

algorithm
format(level=0, indent=' ') -> string)
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

indent : string

string replicated once for each indent level then prepended to output line

This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.

format_lines(level=0) → [(level, string),...]
Parameters:
level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI’s with indentation controls. See nss.nss.indented_format() for a complete explanation.

public_key

PublicKey object

nss.nss.algtag_to_mechanism(algtag) → mechanism
Parameters:
algtag : int

algorithm tag (e.g. SEC_OID_*)

Returns the key mechanism enumeration constant (CKM_*) given an algorithm tag. Throws a KeyError exception if the algorithm tag is invalid.

nss.nss.base64_to_binary(text) → SecItem
Parameters:
text : string

string containing base64 data.

Convert the base64 encoded data to binary data.

The text is assumed to contain base64 text. The base64 text may optionally be wrapped in a PEM header and footer.

Returns a SecItem containg the binary data.

Note, a SecItem can be initialized directly from base64 text by utilizing the ascii parameter to the SecItem constructor, thus the two are equivalent:

sec_item = nss.base64_to_binary(text) sec_tiem = nss.SecItem(text, ascii=True)
nss.nss.cert_crl_reason_from_name()

crl_reason_from_name(name) -> int

Parameters:
name : string

name of CERTCRLEntryReasonCode constant

Given the name of a CERTCRLEntryReasonCode constant return it’s integer constant The string comparison is case insensitive and will match with or without the crlEntry prefix

nss.nss.cert_crl_reason_name()

crl_reason_name(reason) -> string

Parameters:
reason : int

CERTCRLEntryReasonCode constant

Given a CERTCRLEntryReasonCode constant return it’s name as a string

nss.nss.cert_general_name_type_from_name()

general_name_type_from_name(name) -> int

Parameters:
name : string

name of CERTGeneralNameType constant

Given the name of a CERTGeneralNameType constant return it’s integer constant The string comparison is case insensitive and will match with or without the cert prefix

nss.nss.cert_general_name_type_name()

general_name_type_name(type) -> string

Parameters:
type : int

CERTGeneralNameType constant

Given a CERTGeneralNameType constant return it’s name as a string

nss.nss.cert_type_flags(flags, repr_kind=AsEnumName) → ['flag_name', ...]
Parameters:
flags : int

KU_* bit flags

repr_kind : RepresentationKind constant

Specifies what the contents of the returned list will be. May be one of:

AsEnum

The enumerated constant as an integer value.

AsEnumName

The name of the enumerated constant as a string.

AsEnumDescription

A friendly human readable description of the enumerated constant as a string.

Given an integer with NS_CERT_TYPE_* (e.g. nss.NS_CERT_TYPE_SSL_SERVER) bit flags return a sorted list of their string names.

nss.nss.cert_usage_flags(flags, repr_kind=AsEnumDescription) → ['flag_name', ...]
Parameters:
flags : int

certificateUsage* bit flags

repr_kind : RepresentationKind constant

Specifies what the contents of the returned list will be. May be one of:

AsEnum

The enumerated constant as an integer value.

AsEnumName

The name of the enumerated constant as a string.

AsEnumDescription

A friendly human readable description of the enumerated constant as a string.

Given an integer with certificateUsage* (e.g. nss.certificateUsageSSLServer) bit flags return a sorted list of their string names.

nss.nss.clear_ocsp_cache()

Removes all items currently stored in the OCSP cache.

nss.nss.create_context_by_sym_key(mechanism, operation, sym_key, sec_param=None) → PK11Context
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

operation : int

type of operation this context will be doing. A (CKA_*) constant (e.g. CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, CKA_DIGEST)

sym_key : PK11SymKey object

symmetric key

sec_param : SecItem object or None

mechanism parameters used to build this context or None.

Create a context from a symmetric key)

nss.nss.create_digest_context(hash_alg) → PK11Context
Parameters:
hash_alg : int

hash algorithm enumeration (SEC_OID_*) e.g.: SEC_OID_MD5, SEC_OID_SHA1, SEC_OID_SHA256, SEC_OID_SHA512, etc.

Create a context for performing digest (hash) operations)

nss.nss.create_pbev2_algorithm_id(pbe_alg=SEC_OID_PKCS5_PBKDF2, cipher_alg=SEC_OID_AES_256_CBC, prf_alg=SEC_OID_HMAC_SHA1, key_length=0, iterations=100, salt=None) → AlgorithmID
Parameters:
pbe_alg : may be one of integer, string or SecItem (see below)

password based encryption algorithm

cipher_alg : may be one of integer, string or SecItem (see below)

cipher algorithm

prf_alg : may be one of integer, string or SecItem (see below)

pseudo-random function algorithm

key_length : int

Number of octets in derived key DK. Must be a valid value for the cipher_alg. If zero then NSS will select the longest key length appropriate for the cipher

iterations : int

Number of times the pseudo-random function is applied to generate the symmetric key.

salt : SecItem or str or any buffer compatible object or None

Cyrptographic salt. If None a random salt will be generated.

The default values are appropriate for most users desiring a PKCS5v2 PBE symmetric key.

The pbe, cipher and prf algorithms may be specified in any of the following manners:

  • integer:: A SEC OID enumeration constant, also known as a tag (i.e. SEC_OID_*) for example SEC_OID_PKCS5_PBKDF2.
  • string:: A string for the tag name (e.g. ‘SEC_OID_PKCS5_PBKDF2’) The ‘SEC_OID_’ prefix is optional. A string in dotted decimal representation, for example ‘OID.1.2.840.113549.1.5.12’. The ‘OID.’ prefix is optional. Case is not significant.
  • SecItem:: A SecItem object encapsulating the OID in
    DER format.
nss.nss.data_to_hex(data, octets_per_line=0, separator=':') → string or list of strings
Parameters:
data : buffer

Binary data

octets_per_line : integer

Number of octets formatted on one line, if 0 then return a single string instead of an array of lines

separator : string

String used to seperate each octet If None it will be as if the empty string had been passed and no separator will be used.

Format the binary data as hex string(s). Either a list of strings is returned or a single string.

If octets_per_line is greater than zero then a list of strings will be returned where each string contains octets_per_line number of octets (except for the last string in the list which will contain the remainder of the octets). Returning a list of “lines” makes it convenient for a caller to format a block of hexadecimal data with line wrapping. If octets_per_line is greater than zero indicating a list result is desired a list is always returned even if the number of octets would produce only a single line.

If octets_per_line is zero then a single string is returned, (no line splitting is performed). This is the default.

The separator string is used to separate each octet. If None it will be as if the empty string had been passed and no separator will be used.

nss.nss.decode_der_crl(der_crl, type=SEC_CRL_TYPE, decode_options=CRL_DECODE_DEFAULT_OPTIONS) → SignedCRL
Parameters:
der_crl : SecItem object

DER encoded CRL data encapsulated in a SECItem.

type : int

revocation list type

may be one of:
  • SEC_CRL_TYPE
  • SEC_KRL_TYPE
decode_options : int
bit-wise OR of the following flags:
  • CRL_DECODE_DONT_COPY_DER
  • CRL_DECODE_SKIP_ENTRIES
  • CRL_DECODE_KEEP_BAD_CRL
  • CRL_DECODE_ADOPT_HEAP_DER

or use CRL_DECODE_DEFAULT_OPTIONS

nss.nss.der_universal_secitem_fmt_lines(sec_item, level=0, octets_per_line=0, separator=':') → list of (indent, string) tuples
Parameters:
sec_item : SecItem object

A SecItem containing a DER encoded ASN1 universal type

level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

octets_per_line : integer

Number of octets formatted on one line, if 0 then return a single string instead of an array of lines

separator : string

String used to seperate each octet If None it will be as if the empty string had been passed and no separator will be used.

Given a SecItem in DER format which encodes a ASN.1 universal type convert the item to a string and return a list of (indent, string) tuples.

nss.nss.disable_ocsp_checking(certdb=get_default_certdb())
Parameters:
certdb : CertDB object or None

CertDB certificate database object, if None then the default certdb will be supplied by calling nss.get_default_certdb().

Turns off OCSP checking for the given certificate database. It will raise an exception with SEC_ERROR_OCSP_NOT_ENABLED as the error code if OCSP checking is not enabled. It is safe to call it when OCSP checking is disabled, you can just ignore the exception if it is easier to just call it than to remember if it was enabled.

nss.nss.disable_ocsp_default_responder(certdb=get_default_certdb())
Parameters:
certdb : CertDB object or None

CertDB certificate database object, if None then the default certdb will be supplied by calling nss.get_default_certdb().

Turns off use of a default responder when OCSP checking. (Does nothing if use of a default responder is not enabled.)

nss.nss.dump_certificate_cache_info()

Dump the contents of the certificate cache and the temporary cert store to stdout.

Use this as a debugging aid to detect leaked references of certs at shutdown time. For example if nss.nss_shutdown() throws a SEC_ERROR_BUSY exception.

nss.nss.enable_ocsp_checking(certdb=get_default_certdb())
Parameters:
certdb : CertDB object or None

CertDB certificate database object, if None then the default certdb will be supplied by calling nss.get_default_certdb().

Turns on OCSP checking for the given certificate database.

nss.nss.enable_ocsp_default_responder(certdb=get_default_certdb())
Parameters:
certdb : CertDB object or None

CertDB certificate database object, if None then the default certdb will be supplied by calling nss.get_default_certdb().

Turns on use of a default responder when OCSP checking. If OCSP checking is already enabled, this will make subsequent checks go directly to the default responder. (The location of the responder and the nickname of the responder cert must already be specified.) If OCSP checking is not enabled, this will be recorded and take effect whenever it is enabled.

nss.nss.find_cert_from_nickname(nickname[, user_data1, ...]) → Certificate
Parameters:
nickname : string

certificate nickname to search for

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

A nickname is an alias for a certificate subject. There may be multiple certificates with the same subject, and hence the same nickname. This function will return the newest certificate that matches the subject, based on the NotBefore / NotAfter fields of the certificate.

nss.nss.find_certs_from_email_addr(email, [user_data1, ...]) -> (`Certificate`, ...)
Parameters:
email : string

email address.

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Given an email address return a tuple of Certificate objects containing that address.

nss.nss.find_certs_from_nickname(email, [user_data1, ...]) -> (`Certificate`, ...)
Parameters:
nickname : string

certificate nickname.

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Given a certificate nickname return a tuple of Certificate objects matching that nickname.

nss.nss.find_key_by_any_cert(cert[, user_data1, ...]) → Certificate
Parameters:
cert : Certificate object

certificate whose private key is being searched for

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Finds the private key associated with a specified certificate in any available slot.

nss.nss.find_slot_by_name(name) → `PK11Slot`
Parameters:
name : string

slot name

Given a slot name return a PK11Slot object.

nss.nss.fingerprint_format_lines(data, level=0)
Parameters:
data : SecItem or str or any buffer compatible object

Data to initialize the certificate request from, must be in DER format

level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Generates digests of data (i.e. fingerprint) and formats it into line tuples for text output.

nss.nss.generate_new_param(mechanism, sym_key=None) → SecItem
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

sym_key : PK11SymKey object or None

symmetric key or None

Return a SecItem containing a encryption param.

nss.nss.generate_random(num_bytes) → string
Parameters:
num_bytes : integer

Number of num_bytes to generate (must be non-negative)

Generates random data..

nss.nss.get_all_tokens(mechanism=CKM_INVALID_MECHANISM, need_rw=False, load_certs=False, pin_args=None) -> (PK11Slot, ...)
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*). Use CKM_INVALID_MECHANISM to get all tokens.

need_rw : boolean

need read/write

load_certs : boolean

load certificates

pin_args : tuple

Extra parameters which will be passed to the password callback function.

Return a tuple of PK11Slot objects.

Example:

import nss.nss as nss
nss.nss_init_nodb()

slots = nss.get_all_tokens()
for slot in slots:
    print slot
    print

Slot Name:                         NSS User Private Key and Certificate Services
Token Name:                        NSS Certificate DB
Is Hardware:                       False
Is Present:                        True
Is Read Only:                      True
Is Internal:                       True
Needs Login:                       False
Needs User Init:                   True
Is Friendly:                       True
Is Removable:                      False
Has Protected Authentication Path: False
Is Disabled:                       False (no reason)
Has Root Certs:                    False
Best Wrap Mechanism:               CKM_DES3_ECB (0x132)

Slot Name:                         NSS Internal Cryptographic Services
Token Name:                        NSS Generic Crypto Services
Is Hardware:                       False
Is Present:                        True
Is Read Only:                      True
Is Internal:                       True
Needs Login:                       False
Needs User Init:                   True
Is Friendly:                       True
Is Removable:                      False
Has Protected Authentication Path: False
Is Disabled:                       False (no reason)
Has Root Certs:                    False
Best Wrap Mechanism:               CKM_DES3_ECB (0x132)
nss.nss.get_best_slot(mechanism[, user_data1, ...]) → PK11Slot
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Find the best slot which supports the given mechanism.

nss.nss.get_block_size(mechanism, sec_param=None) → int
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

sec_param : SecItem object or None

mechanism parameters used to build this context or None.

Get the mechanism block size

nss.nss.get_cert_nicknames(certdb, what[, user_data1, ...]) → name0, ...
Parameters:
certdb : CertDB object

CertDB certificate database object

what : integer
one of:
  • SEC_CERT_NICKNAMES_ALL
  • SEC_CERT_NICKNAMES_USER
  • SEC_CERT_NICKNAMES_SERVER
  • SEC_CERT_NICKNAMES_CA
user_dataN : object

zero or more caller supplied parameters which will be passed to the password callback function

Returns a tuple of the nicknames of the certificates in a specified certificate database.

nss.nss.get_default_certdb()

Returns the default certificate database as a CertDB object

nss.nss.get_internal_key_slot() → PK11Slot

Get the default internal key slot.

nss.nss.get_internal_slot() → PK11Slot

Get the default internal slot.

nss.nss.get_iv_length(mechanism) → algtag
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

Returns the length of the mechanism’s initialization vector.

nss.nss.get_pad_mechanism(mechanism) → int
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

Determine appropriate mechanism to use when padding is required. If the mechanism does not map to a padding mechanism return the mechanism.

nss.nss.get_use_pkix_for_validation() → flag

Returns the current value of the flag used to enable or disable the use of PKIX for certificate validation. See also: set_use_pkix_for_validation.

nss.nss.hash_buf()

hash_buf(hash_alg, data) –> digest

Parameters:
hash_alg : int

hash algorithm enumeration (SEC_OID_*) e.g.: SEC_OID_MD5, SEC_OID_SHA1, SEC_OID_SHA256, SEC_OID_SHA512, etc.

data : buffer or string

buffer the digest will be computed for

Computes a digest according to the hash_alg type. Return the digest data as buffer object.

Note, if a hexidecimal string representation is desired then pass result to data_to_hex()

nss.nss.import_crl(slot, der_crl, url, type, import_options, decode_options[, user_data1, ...]) → SignedCRL
Parameters:
slot : PK11Slot object

designated PK11 slot

der_crl : SecItem object

signed DER CRL data encapsulated in a SecItem object.

url : string

URL of the CRL

type : int

revocation list type

may be one of:
  • SEC_CRL_TYPE
  • SEC_KRL_TYPE
import_options : int
bit-wise OR of the following flags:
  • CRL_IMPORT_BYPASS_CHECKS

or use CRL_IMPORT_DEFAULT_OPTIONS

decode_options : int
bit-wise OR of the following flags:
  • CRL_DECODE_DONT_COPY_DER
  • CRL_DECODE_SKIP_ENTRIES
  • CRL_DECODE_KEEP_BAD_CRL
  • CRL_DECODE_ADOPT_HEAP_DER

or use CRL_DECODE_DEFAULT_OPTIONS

user_dataN : object

zero or more caller supplied parameters which will be passed to the password callback function

nss.nss.import_sym_key(slot, mechanism, origin, operation, key_data[, user_data1, ...]) → PK11SymKey
Parameters:
slot : PK11Slot object

designated PK11 slot

mechanism : int

key mechanism enumeration constant (CKM_*)

origin : int

PK11 origin enumeration (PK11Origin*) e.g. PK11_OriginDerive, PK11_OriginUnwrap, etc.

operation : int

type of operation this context will be doing. A (CKA_*) constant (e.g. CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, CKA_DIGEST)

key_data: SecItem object

key data encapsulated in a SECItem used to build the symmetric key.

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Create a PK11SymKey from data)

nss.nss.indented_format(line_fmt_tuples, indent_len=4) → string

The function supports the display of complex objects which may be composed of other complex objects. There is often a need to output section headers or single strings and lists of <attribute,value> pairs (the attribute in this discussion is called a label), or even blank lines. All of these items should line up in columns at different indentation levels in order to visually see the structure.

It would not be flexible enough to have object formatting routines which simply returned a single string with all the indentation and formatting pre-applied. The indentation width may not be what is desired. Or more importantly you might not be outputting to text display. It might be a GUI which desires to display the information. Most GUI’s want to handle each string seperately and control indentation and the visibility of each item (e.g. a tree control).

At the same time we want to satisfy the need for easy and simple text output. This routine will do that, e.g.:

print indented_format(obj.format_lines())

To accomodate necessary flexibility the object formatting methods (format_lines()) return a list of tuples. Each tuple represents a single line with the first tuple item being the indentation level for the line. There may be 0,1 or 2 additional strings in the tuple which are to be output on the line. A single string are usually one of two things, either a section header or data that has been continuted onto multiple lines. Two strings usually represent a <attribute,value> pair with the first string being a label (e.g. attribute name).

Each tuple may be:

(int,)
1-value tuple, no strings, e.g. blank line.
(int, string)
2-value tuple, output string at indent level.
(int, string, string)
3-value tuple, first string is a label, second string is a value. Starting at the indent level output the label, then follow with the value. By keeping the label separate from the value the ouput formatter may elect to align the values in vertical columns for adjacent lines.

Example:

# This list of tuples,

[(0, 'Constraints'),
 (1, 'min:', '0')
 (1, 'max:', '100'),
 (1, 'Filter Data'),
 (2, 'ab bc de f0 12 34 56 78 9a bc de f0')
 (2, '12 34 56 78 9a bc de f0 12 34 56 78')
]

# would product this output

Constraints
    min: 0
    max: 100
    Filter Data:
       ab bc de f0 12 34 56 78 9a bc de f0
       12 34 56 78 9a bc de f0 12 34 56 78
Parameters:
line_fmt_tuples : [(level, …),…]

A list of tuples. First tuple value is the indentation level followed by optional strings for the line.

indent_len : int

Number of space characters repeated for each level and prepended to the line string.

nss.nss.is_fips()

pk11_is_fips() -> bool

Returns True if the internal module has FIPS enabled, False otherwise.

nss.nss.key_mechanism_type_from_name(name) → int
Parameters:
name : string

name of key mechanism enumeration constant (CKM_*)

Given the name of a key mechanism enumeration constant (CKM_*) return it’s integer constant The string comparison is case insensitive and will match with or without the CKM_ prefix

nss.nss.key_mechanism_type_name(mechanism) → string
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

Given a key mechanism enumeration constant (CKM_*) return it’s name as a string

nss.nss.key_usage_flags(flags, repr_kind=AsEnumName) → ['flag_name', ...]
Parameters:
flags : int

KU_* bit flags

repr_kind : RepresentationKind constant

Specifies what the contents of the returned list will be. May be one of:

AsEnum

The enumerated constant as an integer value.

AsEnumName

The name of the enumerated constant as a string.

AsEnumDescription

A friendly human readable description of the enumerated constant as a string.

Given an integer with KU_* (e.g. nss.KU_DIGITAL_SIGNATURE) bit flags return a sorted list of their string names.

nss.nss.list_certs(type, [user_data1, ...]) -> (`Certificate`, ...)
Parameters:
type : int

PK11CertList* enumerated constant.

user_dataN : object …

zero or more caller supplied parameters which will be passed to the password callback function

Given the type of certificates to list return a tuple of Certificate objects matching that type.

nss.nss.make_line_fmt_tuples(level, obj) → [(level, str), ...]
Parameters:
obj : object

If obj is a tuple or list then each member will be wrapped in a 2-tuple of (level, str). If obj is a scalar object then obj will be wrapped in a 2-tuple of (level, obj)

level : integer

Initial indentation level, all subsequent indents are relative to this starting level.

Return a list of line formatted tuples sutible to passing to indented_format(). Each tuple consists of a integer level value and a string object. This is equivalent to: [(level, str(x)) for x in obj]. As a special case convenience if obj is a scalar object (i.e. not a list or tuple) then [(level, str(obj))] will be returned.

nss.nss.md5_digest()

md5_digest(data) –> digest

Parameters:
data : buffer or string

buffer the digest will be computed for

Returns 16 octet MD5 digest data as buffer object.

Note, if a hexidecimal string representation is desired then pass result to data_to_hex()

nss.nss.mechanism_to_algtag(mechanism) → algtag
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

Returns the algtag given key mechanism enumeration constant (CKM_*) Throws an KeyError exception if the mechanism is invalid.

nss.nss.need_pw_init()

pk11_need_pw_init() -> bool

Returns True if the internal slot needs to be initialized, False otherwise.

The internal slot token should be initalized if:

The token is not initialized

PK11Slot.need_login() == True and PK11Slot.need_user_init() == True

Or

The token has a NULL password.

PK11Slot.need_login() == False and PK11Slot.need_user_init() == False
CKF_LOGIN_REQUIRED CKF_USER_PIN_INITIALIZED CKF_TOKEN_INITIALIZED
False False True
True False False
False True True
True True True

PK11Slot.need_login() == CKF_LOGIN_REQUIRED

PK11Slot.need_user_init() == !CKF_USER_PIN_INITIALIZED

nss.nss.nss_get_version() → string

Return a string of the NSS library version

nss.nss.nss_init(cert_dir)
Parameters:
cert_dir : string

Pathname of the directory where the certificate, key, and security module databases reside.

Sets up configuration files and performs other tasks required to run Network Security Services. nss.nss_init() differs from nss.nss_init_read_write() because the internal PK11 slot (see nss.get_internal_slot()) is created in Read Only (RO) mode as opposed to Read Write (RW) mode.

nss.nss.nss_init_context(cert_dir=None, cert_prefix=None, key_prefix=None, secmod_name=None, init_params=None, flags=0) → `InitContext`
Parameters:
cert_dir : string

Pathname of the directory where the certificate, key, and security module databases reside.

cert_prefix : string

Prefix added to the beginning of the certificate database, for example,”https-server1-“.

key_prefix : string

Prefix added to the beginning of the key database, for example, “https-server1-“.

secmod_name : string

Name of the security module database, usually “secmod.db”.

init_params : InitContext object

Object with a set of initialization parameters. See InitContext.

flags

Bit flags that specify how NSS should be initialized.

nss_init_context() initializes NSS within a context and returns a InitContext object. Contexts are used when multiple entities within a single process wish to use NSS without colliding such as libraries.

You must hold onto the returned InitContext object and call shutdown on it when you are done. The context will automatically be shutdown when the InitContext object is destroyed if you have not already shut it down.

By default nss_initialize() and nss_init_context() open the internal PK11 slot (see get_internal_slot()) in Read Write (RW) mode as opposed to nss_init() which opens it in Read Only (RO) mode. If you want RO mode you pass the NSS_INIT_READONLY flag.

The flags parameter is a bitwise OR of the following flags:

NSS_INIT_READONLY
Open the databases read only.
NSS_INIT_NOCERTDB
Don’t open the cert DB and key DB’s, just initialize the volatile certdb.
NSS_INIT_NOMODDB
Don’t open the security module DB, just initialize the PKCS #11 module.
NSS_INIT_FORCEOPEN
Continue to force initializations even if the databases cannot be opened.
NSS_INIT_NOROOTINIT
Don’t try to look for the root certs module automatically.
NSS_INIT_OPTIMIZESPACE
Optimize for space instead of speed. Use smaller tables and caches.
NSS_INIT_PK11THREADSAFE
Only load PKCS#11 modules that are thread-safe, i.e., that support locking - either OS locking or NSS-provided locks . If a PKCS#11 module isn’t thread-safe, don’t serialize its calls; just don’t load it instead. This is necessary if another piece of code is using the same PKCS#11 modules that NSS is accessing without going through NSS, for example, the Java SunPKCS11 provider.
NSS_INIT_PK11RELOAD
Ignore the CKR_CRYPTOKI_ALREADY_INITIALIZED error when loading PKCS#11 modules. This is necessary if another piece of code is using the same PKCS#11 modules that NSS is accessing without going through NSS, for example, Java SunPKCS11 provider.
NSS_INIT_NOPK11FINALIZE
Never call C_Finalize on any PKCS#11 module. This may be necessary in order to ensure continuous operation and proper shutdown sequence if another piece of code is using the same PKCS#11 modules that NSS is accessing without going through NSS, for example, Java SunPKCS11 provider. The following limitation applies when this is set : SECMOD_WaitForAnyTokenEvent will not use C_WaitForSlotEvent, in order to prevent the need for C_Finalize. This call will be emulated instead.
NSS_INIT_RESERVED
Currently has no effect, but may be used in the future to trigger better cooperation between PKCS#11 modules used by both NSS and the Java SunPKCS11 provider. This should occur after a new flag is defined for C_Initialize by the PKCS#11 working group.
NSS_INIT_COOPERATE
Sets the above four recommended options for applications that use both NSS and the Java SunPKCS11 provider.

Hint: You can obtain a printable representation of the flags via nss_init_flags.

nss.nss.nss_init_flags(flags, repr_kind=AsEnumName) → ['flag_name', ...]
Parameters:
flags : int

NSS_INIT* bit flags

repr_kind : RepresentationKind constant

Specifies what the contents of the returned list will be. May be one of:

AsEnum

The enumerated constant as an integer value.

AsEnumName

The name of the enumerated constant as a string.

AsEnumDescription

A friendly human readable description of the enumerated constant as a string.

Given an integer with NSS_INIT* (e.g. nss.NSS_INIT_READONLY) bit flags return a sorted list of their string names.

nss.nss.nss_init_nodb()

Performs tasks required to run Network Security Services without setting up configuration files. Important: This NSS function is not intended for use with SSL, which requires that the certificate and key database files be opened.

nss_init_nodb opens only the temporary database and the internal PKCS #112 module. Unlike nss_init, nss_init_nodb allows applications that do not have access to storage for databases to run raw crypto, hashing, and certificate functions. nss_init_nodb is not idempotent, so call it only once. The policy flags for all cipher suites are turned off by default, disallowing all cipher suites. Therefore, an application cannot use NSS to perform any cryptographic operations until after it enables appropriate cipher suites by calling one of the SSL Export Policy Functions.

nss.nss.nss_init_read_write(cert_dir)
Parameters:
cert_dir : string

Pathname of the directory where the certificate, key, and security module databases reside.

Sets up configuration files and performs other tasks required to run Network Security Services. nss.nss_init_read_write() differs from nss.nss_init() because the internal PK11 slot (see nss.get_internal_slot()) is created in Read Write (RW) mode as opposed to Read Only (RO) mode.

nss.nss.nss_initialize(cert_dir=None, cert_prefix=None, key_prefix=None, secmod_name=None, flags=0)
Parameters:
cert_dir : string

Pathname of the directory where the certificate, key, and security module databases reside.

cert_prefix : string

Prefix added to the beginning of the certificate database, for example,”https-server1-“.

key_prefix : string

Prefix added to the beginning of the key database, for example, “https-server1-“.

secmod_name : string

Name of the security module database, usually “secmod.db”.

flags

Bit flags that specify how NSS should be initialized.

nss_initialize() initializes NSS. It is more flexible than nss_init(), nss_init_read_write(), and nss_init_nodb(). If any of those simpler NSS initialization functions suffices for your needs, call that instead.

By default nss_initialize() and nss_init_context() open the internal PK11 slot (see get_internal_slot()) in Read Write (RW) mode as opposed to nss_init() which opens it in Read Only (RO) mode. If you want RO mode you pass the NSS_INIT_READONLY flag.

The flags parameter is a bitwise OR of the following flags:

NSS_INIT_READONLY
Open the databases read only.
NSS_INIT_NOCERTDB
Don’t open the cert DB and key DB’s, just initialize the volatile certdb.
NSS_INIT_NOMODDB
Don’t open the security module DB, just initialize the PKCS #11 module.
NSS_INIT_FORCEOPEN
Continue to force initializations even if the databases cannot be opened.
NSS_INIT_NOROOTINIT
Don’t try to look for the root certs module automatically.
NSS_INIT_OPTIMIZESPACE
Optimize for space instead of speed. Use smaller tables and caches.
NSS_INIT_PK11THREADSAFE
Only load PKCS#11 modules that are thread-safe, i.e., that support locking - either OS locking or NSS-provided locks . If a PKCS#11 module isn’t thread-safe, don’t serialize its calls; just don’t load it instead. This is necessary if another piece of code is using the same PKCS#11 modules that NSS is accessing without going through NSS, for example, the Java SunPKCS11 provider.
NSS_INIT_PK11RELOAD
Ignore the CKR_CRYPTOKI_ALREADY_INITIALIZED error when loading PKCS#11 modules. This is necessary if another piece of code is using the same PKCS#11 modules that NSS is accessing without going through NSS, for example, Java SunPKCS11 provider.
NSS_INIT_NOPK11FINALIZE
Never call C_Finalize on any PKCS#11 module. This may be necessary in order to ensure continuous operation and proper shutdown sequence if another piece of code is using the same PKCS#11 modules that NSS is accessing without going through NSS, for example, Java SunPKCS11 provider. The following limitation applies when this is set : SECMOD_WaitForAnyTokenEvent will not use C_WaitForSlotEvent, in order to prevent the need for C_Finalize. This call will be emulated instead.
NSS_INIT_RESERVED
Currently has no effect, but may be used in the future to trigger better cooperation between PKCS#11 modules used by both NSS and the Java SunPKCS11 provider. This should occur after a new flag is defined for C_Initialize by the PKCS#11 working group.
NSS_INIT_COOPERATE
Sets the above four recommended options for applications that use both NSS and the Java SunPKCS11 provider.

Hint: You can obtain a printable representation of the flags via nss_init_flags.

nss.nss.nss_is_initialized()

nss_is_initialized() –> bool

Returns whether Network Security Services has already been initialized or not.

nss.nss.nss_shutdown()

Closes the key and certificate databases that were opened by nss_init().

NSS can only shutdown successfully if all NSS objects have been released, otherwise nss_shutdown will fail with the error code SEC_ERROR_BUSY. Here are some tips to make sure nss_shutdown will succeed. [1]

  • If the process is a SSL client make sure you call ssl.clear_session_cache.
  • If the process is a SSL server make sure you call ssl.shutdown_server_session_id_cache().
  • Make sure all sockets have been closed, open SSL sockets hold references NSS objects.
  • Explicitly delete Python objects which contain NSS objects using the del command. [2]
  • Use nss.dump_certificate_cache_info() to provide information about which cached objects may still persist and be responsible for preventing a full NSS shutdown.
[1]If the leaked objects are subsequently released after nss_shutdown is called NSS can be reinitialized with the various NSS initialization routines. In this cass teh SEC_ERROR_BUSY error can be thought of as an informatiive warning.
[2]

This Python binding to NSS wraps each NSS object inside a Python object. Like NSS objects Python objects are reference counted. When the last reference to the Python object disappears the Python object is destroyed. The destructor for a Python object wrapping an NSS object releases the NSS reference to the NSS object. Thus if any Python objects which wrap NSS objects remain “live” nss_shutdown will fail. Python objects are typically released by the Python interpretor when the variable holding the object is assigned a new object or when the variable holding the object goes out of scope. This means you may need to manually delete some objects using the del command rather relying on Python’s automatic garbage collection. Consider this example:

def foo():
nss.nss_init(certdir) sock = ssl.SSLSocket() nss.nss_shutdown()

When nss_shutown() is called the sock object is still alive and holds references to NSS objects. The sock object won’t be released by Python until it goes out of scope when the function exits. Thus the shutdown will fail with SEC_ERROR_BUSY. But you can explicitly force the sock object to be released by explictily deleting it, for example:

def foo():
nss.nss_init(certdir) sock = ssl.SSLSocket() del sock nss.nss_shutdown()

Another way to avoid this issue is to arrange your code such that nss_shutdown is called from a location in your code which is not in scope for any NSS objects created. This also implies you shouldn’t assign NSS objects to globals.

nss.nss.nss_shutdown_context(context)
Parameters:
context : InitContext object

A InitContext returned from a previous call to nss_init_context.

Shutdown NSS for the users of this context. When all contexts have been shutdown NSS will fully shutdown.

nss.nss.nss_version_check()

nss_version_check(version) –> bool

Parameters:
version : string

Required version

Return a boolean that indicates whether the underlying NSS library will perform as the caller expects.

The the version parameter is a string identifier of the NSS library. That string will be compared against a string that represents the actual build version of the NSS library. Return True if supplied version is compatible, False otherwise.

nss.nss.oid_dotted_decimal(oid) → string
Parameters:
oid : may be one of integer, string, SecItem

May be one of:

  • integer:: A SEC OID enumeration constant, also known as a tag (i.e. SEC_OID_*) for example SEC_OID_AVA_COMMON_NAME.
  • string:: A string in dotted decimal representation, for example ‘OID.2.5.4.3’. The ‘OID.’ prefix is optional. Or a string for the tag name (e.g. ‘SEC_OID_AVA_COMMON_NAME’) The ‘SEC_OID_’ prefix is optional. Or one of the canonical abbreviations (e.g. ‘cn’). Case is not significant.
  • SecItem:: A SecItem object encapsulating the OID in DER format.

Given an oid return it’s tag constant as a string.

nss.nss.oid_str(oid) → string
Parameters:
oid : may be one of integer, string, SecItem

May be one of:

  • integer:: A SEC OID enumeration constant, also known as a tag (i.e. SEC_OID_*) for example SEC_OID_AVA_COMMON_NAME.
  • string:: A string in dotted decimal representation, for example ‘OID.2.5.4.3’. The ‘OID.’ prefix is optional. Or a string for the tag name (e.g. ‘SEC_OID_AVA_COMMON_NAME’) The ‘SEC_OID_’ prefix is optional. Or one of the canonical abbreviations (e.g. ‘cn’). Case is not significant.
  • SecItem:: A SecItem object encapsulating the OID in DER format.

Given an oid return it’s description as a string.

nss.nss.oid_tag(oid) → int
Parameters:
oid : may be one of integer, string, SecItem

May be one of:

  • integer:: A SEC OID enumeration constant, also known as a tag (i.e. SEC_OID_*) for example SEC_OID_AVA_COMMON_NAME.
  • string:: A string in dotted decimal representation, for example ‘OID.2.5.4.3’. The ‘OID.’ prefix is optional. Or a string for the tag name (e.g. ‘SEC_OID_AVA_COMMON_NAME’) The ‘SEC_OID_’ prefix is optional. Or one of the canonical abbreviations (e.g. ‘cn’). Case is not significant.
  • SecItem:: A SecItem object encapsulating the OID in DER format.

Given an oid return it’s tag constant.

nss.nss.oid_tag_name(oid) → string
Parameters:
oid : may be one of integer, string, SecItem

May be one of:

  • integer:: A SEC OID enumeration constant, also known as a tag (i.e. SEC_OID_*) for example SEC_OID_AVA_COMMON_NAME.
  • string:: A string in dotted decimal representation, for example ‘OID.2.5.4.3’. The ‘OID.’ prefix is optional. Or a string for the tag name (e.g. ‘SEC_OID_AVA_COMMON_NAME’) The ‘SEC_OID_’ prefix is optional. Or one of the canonical abbreviations (e.g. ‘cn’). Case is not significant.
  • SecItem:: A SecItem object encapsulating the OID in DER format.

Given an oid return it’s tag constant as a string.

nss.nss.param_from_algid(algid) → SecItem
Parameters:
algid : AlgorithmID object

algorithm id

Return a SecItem containing a encryption param derived from a AlgorithmID.

nss.nss.param_from_iv(mechanism, iv=None) → SecItem
Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

iv : SecItem object

initialization vector. If there is no initialization vector you may also pass None or an empty SecItem object (e.g. SecItem())

Return a SecItem to be used as the initialization vector for encryption/decryption.

nss.nss.pk11_attribute_type_from_name(name) → int
Parameters:
name : string

name of PK11 attribute type constant (CKA_*)

Given the name of a PK11 attribute type constant (CKA_*) return it’s integer constant The string comparison is case insensitive and will match with or without the CKA_ prefix

nss.nss.pk11_attribute_type_name(type) → string
Parameters:
type : int

PK11 attribute type constant (CKA_*)

Given a PK11 attribute type constant (CKA_*) return it’s name as a string

nss.nss.pk11_disabled_reason_name(reason) → string
Parameters:
reason : int

PK11 slot disabled reason constant (PK11_DIS_*)

Given a PK11 slot disabled reason constant (PK11_DIS_*) return the constant as a string.

nss.nss.pk11_disabled_reason_str(reason) → string
Parameters:
reason : int

PK11 slot disabled reason constant (PK11_DIS_*)

Given a PK11 slot disabled reason constant (PK11_DIS_*) return a descriptive string

nss.nss.pk11_logout_all()

Logout of every slot for all modules.

nss.nss.pkcs12_cipher_from_name(name) → int
Parameters:
name : string

name of PKCS12_* constant

Given the name of a PKCS12_* constant return it’s integer constant The string comparison is case insensitive and will match with or without the PKCS12_ prefix

nss.nss.pkcs12_cipher_name(cipher) → string
Parameters:
cipher : int

PKCS12_* constant

Given a PKCS12_* constant return it’s name as a string

nss.nss.pkcs12_enable_all_ciphers()
Enables all PKCS12 ciphers, which are:
  • PKCS12_RC2_CBC_40
  • PKCS12_RC2_CBC_128
  • PKCS12_RC4_40
  • PKCS12_RC4_128
  • PKCS12_DES_56
  • PKCS12_DES_EDE3_168
nss.nss.pkcs12_enable_cipher(cipher, enabled)
Parameters:
cipher : integer

The PKCS12 cipher suite enumeration (e.g. PKCS12_DES_EDE3_168, etc.)

enabled : bool or int

True enables, False disables

The cipher may be one of:
  • PKCS12_RC2_CBC_40
  • PKCS12_RC2_CBC_128
  • PKCS12_RC4_40
  • PKCS12_RC4_128
  • PKCS12_DES_56
  • PKCS12_DES_EDE3_168
nss.nss.pkcs12_export()

pkcs12_export(nickname, pkcs12_password, key_cipher=SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC, cert_cipher=SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC, pin_args=None)

Parameters:
nickname : string

Certificate nickname to search for.

pkcs12_password : string

The password used to protect the pkcs12_file.

key_cipher : int

A SEC OID TAG enumerated constant selecting the encryption for the private key (see below). Also see nss.pkcs12_map_cipher() for an alternative method to select the encryption cipher.

cert_cipher : int

A SEC OID TAG enumerated constant selecting the encryption for the certificates (see below). Also see nss.pkcs12_map_cipher() for an alternative method to select the encryption cipher.

pin_args : tuple

Extra parameters which will be passed to the password callback function.

pkcs12_export() is used to export a certificate and private key pair from the NSS database in a protected manner. It produces the binary content of what is typically called a .p12 file (e.g. PKCS12). This function does not write the file, if you want to write a .p12 file you must write it’s output to a file, for example:

pkcs12_data = nss.pkcs12_export(nickname, pkcs12_file_password)
f = open(p12_file_path, 'w')
f.write(pkcs12_data)
f.close()

PKCS #12 provides for not only the protection of the private keys but also the certificate and meta-data associated with the keys. Password based encryption is used to protect private keys (i.e. key_cipher) on export to a PKCS #12 file and also the entire package when allowed (i.e. cert_cipher). If no algorithm is specified it defaults to using ‘PKCS #12 V2 PBE With SHA-1 And 3KEY Triple DES-CBC’ for private key encryption. For historical export control reasons ‘PKCS #12 V2 PBE With SHA-1 And 40 Bit RC2 CBC’ is the default for the overall package encryption when not in FIPS mode and no package encryption when in FIPS mode. The private key is always protected with strong encryption by default.

A list of ciphers follows, the term is the SEC OID TAG followd by a friendly description.

  • symmetric CBC ciphers for PKCS #5 V2:
    SEC_OID_DES_CBC
    DES-CBC.
    SEC_OID_RC2_CBC
    RC2-CBC.
    SEC_OID_RC5_CBC_PAD
    RC5-CBCPad.
    SEC_OID_DES_EDE3_CBC
    DES-EDE3-CBC.
    SEC_OID_AES_128_CBC
    AES-128-CBC.
    SEC_OID_AES_192_CBC
    AES-192-CBC.
    SEC_OID_AES_256_CBC
    AES-256-CBC.
    SEC_OID_CAMELLIA_128_CBC
    CAMELLIA-128-CBC.
    SEC_OID_CAMELLIA_192_CBC
    CAMELLIA-192-CBC.
    SEC_OID_CAMELLIA_256_CBC
    CAMELLIA-256-CBC.
  • PKCS #12 PBE Ciphers:
    SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC4
    PKCS #12 PBE With SHA-1 and 128 Bit RC4.
    SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC4
    PKCS #12 PBE With SHA-1 and 40 Bit RC4.
    SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC
    PKCS #12 PBE With SHA-1 and Triple DES-CBC.
    SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC
    PKCS #12 PBE With SHA-1 and 128 Bit RC2 CBC.
    SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC
    PKCS #12 PBE With SHA-1 and 40 Bit RC2 CBC.
    SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC4
    PKCS #12 V2 PBE With SHA-1 And 128 Bit RC4.
    SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC4
    PKCS #12 V2 PBE With SHA-1 And 40 Bit RC4.
    SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC
    PKCS #12 V2 PBE With SHA-1 And 3KEY Triple DES-CBC.
    SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_2KEY_TRIPLE_DES_CBC
    PKCS #12 V2 PBE With SHA-1 And 2KEY Triple DES-CBC.
    SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC
    PKCS #12 V2 PBE With SHA-1 And 128 Bit RC2 CBC.
    SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC
    PKCS #12 V2 PBE With SHA-1 And 40 Bit RC2 CBC.
  • PKCS #5 PBE Ciphers:
    SEC_OID_PKCS5_PBE_WITH_MD2_AND_DES_CBC
    PKCS #5 Password Based Encryption with MD2 and DES-CBC.
    SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC
    PKCS #5 Password Based Encryption with MD5 and DES-CBC.
    SEC_OID_PKCS5_PBE_WITH_SHA1_AND_DES_CBC
    PKCS #5 Password Based Encryption with SHA-1 and DES-CBC.
nss.nss.pkcs12_map_cipher(cipher, key_length=0) → int
Parameters:
cipher : may be one of integer, string or SecItem

May be one of:

  • integer:: A SEC OID enumeration constant, also known as a tag (i.e. SEC_OID_*) for example SEC_OID_DES_EDE3_CBC.
  • string:: A string for the tag name (e.g. ‘SEC_OID_DES_EDE3_CBC’) The ‘SEC_OID_’ prefix is optional. A string in dotted decimal representation, for example ‘OID.2.5.4.3’. The ‘OID.’ prefix is optional. Case is not significant.
  • SecItem:: A SecItem object encapsulating the OID in DER format.
key_length : int

The number of bits in the key. If zero a default will be selected.

Given an cipher and optionally a key length, map that to a PKCS12 encryption method returned as a SEC_OID tag.

nss.nss.pkcs12_set_nickname_collision_callback(callback)
Parameters:
callback : function pointer

The callback function

When importing a certificate via a PKCS12Decoder object and the nickname is not set or collides with an existing nickname in the NSS database then this callback is invoked to resolve the problem. If no nickname collision callback has been set then an internal default callback will be used instead which calls the NSS function CERT_MakeCANickname (available in the Python binding as Certificate.make_ca_nickname()).

The callback has the signature:

nickname_collision_callback(old_nickname, cert) --> new_nickname, cancel
old_nickname
the preious nickname or None if previous did not exist
cert
the Certificate object being imported.

The callback returns 2 values, the new nickname, and a boolean.

new_nickname
The new nickname to try or None
cancel
boolean indicating if collision resolution should be cancelled
nss.nss.pkcs12_set_preferred_cipher(cipher, enabled)
Parameters:
cipher : integer

The PKCS12 cipher suite enumeration (e.g. PKCS12_DES_EDE3_168, etc.)

enabled : bool or int

True enables, False disables

This function enables or disables the preferred flag on a PKCS cipher. The default preferred cipher is PKCS12_RC2_CBC_40.

The cipher may be one of:
  • PKCS12_RC2_CBC_40
  • PKCS12_RC2_CBC_128
  • PKCS12_RC4_40
  • PKCS12_RC4_128
  • PKCS12_DES_56
  • PKCS12_DES_EDE3_168
nss.nss.pub_wrap_sym_key(mechanism, pub_key, sym_key) → SecItem
Parameters:
mechanism : int

CK_MECHANISM_TYPE enumerated constant

pub_key : PublicKey object

Public key used to wrap.

sym_key : PK11SymKey object

Symmetric key that will be wrapped.

Returns:

Wrapped symmetric key as SecItem

Wraps a public key wrap (which only RSA can do).

nss.nss.read_der_from_file(file, ascii=False) → SecItem
Parameters:
file : file name or file object

If string treat as file path to open and read, if file object read from file object.

ascii : bool

If True treat file contents as ascii data. If PEM delimiters are found strip them. Then base64 decode the contents.

Read the contents of a file and return as a SecItem object. If file is a string then treat it as a file pathname and open and read the contents of that file. If file is a file object then read the contents from the file object

If the file contents begin with a PEM header then treat the the file as PEM encoded and decode the payload into DER form. Otherwise the file contents is assumed to already be in DER form. The returned SecItem contains the DER contents of the file.

nss.nss.read_hex(input, separators=", :tn") → buffer
Parameters:
input : string

string containing hexadecimal data

separators : string or None

string containing set of separator characters Any character encountered during parsing which is in this string will be skipped and considered a separator between pairs of hexadecimal characters.

Parse a string containing hexadecimal data and return a buffer object containing the binary octets. Each octet in the string is represented as a pair of case insensitive hexadecimal characters (0123456789abcdef). Each octet must be a pair of characters. Octets may optionally be preceded by 0x or 0X. Octets may be separated by separator characters specified in the separators string. The separators string is a set of characters. Any character in the separators character set will be ignored when it occurs between octets. If no separators should be considered then pass an empty string.

Using the default separators each of these strings is valid input representing the same 8 octet sequence:

01, 23, 45, 67, 89, ab, cd, ef 01, 23, 45, 67, 89, AB, CD, EF 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef 01:23:45:67:89:ab:cd:ef 0123456789abcdef 01 23 45 67 89 ab cd ef 0x010x230x450x670x890xab0xcd0xef

nss.nss.set_ocsp_cache_settings(max_cache_entries, min_secs_till_next_fetch, max_secs_till_next_fetch)
Parameters:
max_cache_entries : int

Maximum number of cache entries. Special values, -1 disables the cache, 0 indicates unlimited cache entries.

min_secs_till_next_fetch : int

Whenever an OCSP request was attempted or completed over the network, wait at least this number of seconds before trying to fetch again.

max_secs_till_next_fetch : int

The maximum age of a cached response we allow, until we try to fetch an updated response, even if the OCSP responder expects that a newer information update will not be available yet.

Sets parameters that control NSS’ internal OCSP cache.

nss.nss.set_ocsp_default_responder(certdb, url, nickname)
Parameters:
certdb : CertDB object

CertDB certificate database object.

url : string

The location of the default responder (e.g. “http://foo.com:80/ocsp”) Note that the location will not be tested until the first attempt to send a request there.

nickname : string

The nickname of the cert to trust (expected) to sign the OCSP responses. If the corresponding cert cannot be found, SECFailure is returned.

Specify the location and cert of the default responder. If OCSP checking is already enabled and use of a default responder is also already enabled, all OCSP checking from now on will go directly to the specified responder. If OCSP checking is not enabled, or if it is enabled but use of a default responder is not enabled, the information will be recorded and take effect whenever both are enabled.

nss.nss.set_ocsp_failure_mode(failure_mode)
Parameters:
failure_mode : int

A ocspMode_Failure* constant

Set the desired behaviour on OCSP failures. failure_mode may be one of:

  • ocspMode_FailureIsVerificationFailure
  • ocspMode_FailureIsNotAVerificationFailure
nss.nss.set_ocsp_timeout(seconds)
Parameters:
seconds : int

Maximum number of seconds NSS will wait for an OCSP response.

Configure the maximum time NSS will wait for an OCSP response.

nss.nss.set_password_callback(callback)
Parameters:
callback : function pointer

The callback function

Defines a callback function used by the NSS libraries whenever information protected by a password needs to be retrieved from the key or certificate databases.

Many tokens keep track of the number of attempts to enter a password and do not allow further attempts after a certain point. Therefore, if the retry argument is True, indicating that the password was tried and is wrong, the callback function should return None to indicate that it is unsuccessful, rather than attempting to return the same password again. Failing to terminate when the retry argument is True can result in an endless loop. The user_dataN arguments can also be used to keep track of the number of times the callback has been invoked.

Several functions in the NSS libraries use the password callback function to obtain the password before performing operations that involve the protected information. The extra user_dataN parameters to the password callback function is application-defined and can be used for any purpose. When NSS libraries call the password callback function the value they pass for the user_dataN arguments is determined by ssl.SSLSocket.set_pkcs11_pin_arg().

The callback has the signature:

password_callback(slot, retry, [user_data1, ...]) -> string or None
slot
PK11Slot object
retry
boolean indicating if this is a retry. This implies that the callback has previously returned the wrong password.
user_dataN
zero or more caller supplied optional parameters

The callback should return a string or None to indicate a valid password cannot be supplied. Returning None will prevent the callback from being invoked again.

nss.nss.set_shutdown_callback(callback[, user_data1, ...])
Parameters:
callback : function pointer or None

The callback function. If None cancel the previous callback

user_dataN : object

zero or more caller supplied parameters which will be passed to the shutdown callback function

Defines a callback function which is invoked when NSS is shutdown. If the callback is None the previous callback is cancelled.

After NSS is shutdown the shutdown callback is cancelled, you must reset the shutdown callback again after initializing NSS.

The callback has the signature:

shutdown_callback(nss_data, [user_data1, ...]) -> bool
nss_data
dict of NSS values (currently empty)
user_dataN
zero or more caller supplied optional parameters

The callback should return True for success. If it returns False the NSS shutdown function will complete but will result in an error.

nss.nss.set_use_pkix_for_validation(flag) → prev_flag
Parameters:
flag : bool

Boolean flag, True to enable PKIX validation, False to disable PKIX validation.

Sets the flag to enable or disable the use of PKIX for certificate validation. Returns the previous value of the flag. See also: get_use_pkix_for_validation.

nss.nss.sha1_digest()

sha1_digest(data) –> digest

Parameters:
data : buffer or string

buffer the digest will be computed for

Returns 20 octet SHA1 digest data as buffer object.

Note, if a hexidecimal string representation is desired then pass result to data_to_hex()

nss.nss.sha256_digest()

sha256_digest(data) –> digest

Parameters:
data : buffer or string

buffer the digest will be computed for

Returns 32 octet SHA256 digest data as buffer object.

Note, if a hexidecimal string representation is desired then pass result to data_to_hex()

nss.nss.sha512_digest()

sha512_digest(data) –> digest

Parameters:
data : buffer or string

buffer the digest will be computed for

Returns 64 octet SHA512 digest data as buffer object.

Note, if a hexidecimal string representation is desired then pass result to data_to_hex()

nss.nss.token_exists()

pk11_token_exists(mechanism) -> bool

Parameters:
mechanism : int

key mechanism enumeration constant (CKM_*)

Return True if a token is available which can perform the desired mechanism, False otherwise.

nss.nss.x509_alt_name(sec_item, repr_kind=AsString) -> (SecItem, ...)
Parameters:
sec_item : SecItem object

A SecItem containing a DER encoded alternative name extension.

repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsObject

The general name as a nss.GeneralName object

AsString

The general name as a string. (e.g. “http://crl.geotrust.com/crls/secureca.crl”)

AsTypeString
The general name type as a string.

(e.g. “URI”)

AsTypeEnum
The general name type as a general name type enumerated constant.

(e.g. nss.certURI )

AsLabeledString

The general name as a string with it’s type prepended. (e.g. “URI: http://crl.geotrust.com/crls/secureca.crl

Return a tuple of GeneralNames according the representation kind.

nss.nss.x509_cert_type(bitstr, repr_kind=AsEnumDescription) -> (str, ...)
Parameters:
bitstr : SecItem object

A SecItem containing a DER encoded bit string.

repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsEnum

The enumerated constant. (e.g. nss.NS_CERT_TYPE_SSL_SERVER)

AsEnumDescription
A friendly human readable description of the enumerated constant as a string.

(e.g. “SSL Server”)

AsIndex

The bit position within the bit string.

Return a tuple of string name for each enabled bit in the key usage bit string.

nss.nss.x509_ext_key_usage(sec_item, repr_kind=AsString) -> (obj, ...)
Parameters:
sec_item : SecItem object

A SecItem containing a DER encoded sequence of OID’s

repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsObject

Each extended key usage will be a SecItem object embedding the OID in DER format.

AsString

Each extended key usage will be a descriptive string. (e.g. “TLS Web Server Authentication Certificate”)

AsDottedDecimal

Each extended key usage will be OID rendered as a dotted decimal string. (e.g. “OID.1.3.6.1.5.5.7.3.1”)

AsEnum

Each extended key usage will be OID tag enumeration constant (int). (e.g. nss.SEC_OID_EXT_KEY_USAGE_SERVER_AUTH)

Return a tuple of OID’s according the representation kind.

nss.nss.x509_key_usage(bitstr, repr_kind=AsEnumDescription) -> (str, ...)
Parameters:
bitstr : SecItem object

A SecItem containing a DER encoded bit string.

repr_kind : RepresentationKind constant

Specifies what the contents of the returned tuple will be. May be one of:

AsEnum

The enumerated constant. (e.g. nss.KU_DIGITAL_SIGNATURE)

AsEnumDescription
A friendly human readable description of the enumerated constant as a string.

(e.g. “Digital Signature”)

AsIndex

The bit position within the bit string.

Return a tuple of string name for each enabled bit in the key usage bit string.