sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def convert(input, output=None, options={}): """Converts a supported ``input_format`` (*oldhepdata*, *yaml*) to a supported ``output_format`` (*csv*, *root*, *yaml*, *yoda*). :param input: location of input file for *oldhepdata* format or input directory for *yaml* format :param output: location of output directory to which converted files will be written :param options: additional options such as ``input_format`` and ``output_format`` used for conversion :type input: str :type output: str :type options: dict :raise ValueError: raised if no ``input_format`` or ``output_format`` is specified """ if 'input_format' not in options and 'output_format' not in options: raise ValueError("no input_format and output_format specified!") input_format = options.get('input_format', 'yaml') output_format = options.get('output_format', 'yaml') parser = Parser.get_concrete_class(input_format)(**options) writer = Writer.get_concrete_class(output_format)(**options) if not output and not writer.single_file_output: raise ValueError("this output_format requires specifying 'output' argument") # if no output was specified create proxy output to which writer can insert data _output = output if not _output: _output = StringIO.StringIO() writer.write(parser.parse(input), _output) # if no output was specified return output if not output: return _output.getvalue()
Converts a supported ``input_format`` (*oldhepdata*, *yaml*) to a supported ``output_format`` (*csv*, *root*, *yaml*, *yoda*). :param input: location of input file for *oldhepdata* format or input directory for *yaml* format :param output: location of output directory to which converted files will be written :param options: additional options such as ``input_format`` and ``output_format`` used for conversion :type input: str :type output: str :type options: dict :raise ValueError: raised if no ``input_format`` or ``output_format`` is specified
entailment
def _write_packed_data(self, data_out, table): """This is kind of legacy function - this functionality may be useful for some people, so even though now the default of writing CSV is writing unpacked data (divided by independent variable) this method is still available and accessible if ```pack``` flag is specified in Writer's options :param output: output file like object to which data will be written :param table: input table :type table: hepdata_converter.parsers.Table """ headers = [] data = [] qualifiers_marks = [] qualifiers = {} self._extract_independent_variables(table, headers, data, qualifiers_marks) for dependent_variable in table.dependent_variables: self._parse_dependent_variable(dependent_variable, headers, qualifiers, qualifiers_marks, data) self._write_metadata(data_out, table) self._write_csv_data(data_out, qualifiers, qualifiers_marks, headers, data)
This is kind of legacy function - this functionality may be useful for some people, so even though now the default of writing CSV is writing unpacked data (divided by independent variable) this method is still available and accessible if ```pack``` flag is specified in Writer's options :param output: output file like object to which data will be written :param table: input table :type table: hepdata_converter.parsers.Table
entailment
def digest(algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY): """ <Purpose> Provide the caller with the ability to create digest objects without having to worry about crypto library availability or which library to use. The caller also has the option of specifying which hash algorithm and/or library to use. # Creation of a digest object using defaults or by specifying hash # algorithm and library. digest_object = securesystemslib.hash.digest() digest_object = securesystemslib.hash.digest('sha384') digest_object = securesystemslib.hash.digest('sha256', 'hashlib') # The expected interface for digest objects. digest_object.digest_size digest_object.hexdigest() digest_object.update('data') digest_object.digest() # Added hash routines by this module. digest_object = securesystemslib.hash.digest_fileobject(file_object) digest_object = securesystemslib.hash.digest_filename(filename) <Arguments> algorithm: The hash algorithm (e.g., 'md5', 'sha1', 'sha256'). hash_library: The crypto library to use for the given hash algorithm (e.g., 'hashlib'). <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if an unsupported hashing algorithm is specified, or digest could not be generated with given the algorithm. securesystemslib.exceptions.UnsupportedLibraryError, if an unsupported library was requested via 'hash_library'. <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm)). """ # Are the arguments properly formatted? If not, raise # 'securesystemslib.exceptions.FormatError'. securesystemslib.formats.NAME_SCHEMA.check_match(algorithm) securesystemslib.formats.NAME_SCHEMA.check_match(hash_library) # Was a hashlib digest object requested and is it supported? # If so, return the digest object. if hash_library == 'hashlib' and hash_library in SUPPORTED_LIBRARIES: try: return hashlib.new(algorithm) except ValueError: raise securesystemslib.exceptions.UnsupportedAlgorithmError(algorithm) # Was a pyca_crypto digest object requested and is it supported? elif hash_library == 'pyca_crypto' and hash_library in SUPPORTED_LIBRARIES: #pragma: no cover # TODO: Add support for pyca/cryptography's hashing routines. pass # The requested hash library is not supported. else: raise securesystemslib.exceptions.UnsupportedLibraryError('Unsupported' ' library requested. Supported hash' ' libraries: ' + repr(SUPPORTED_LIBRARIES))
<Purpose> Provide the caller with the ability to create digest objects without having to worry about crypto library availability or which library to use. The caller also has the option of specifying which hash algorithm and/or library to use. # Creation of a digest object using defaults or by specifying hash # algorithm and library. digest_object = securesystemslib.hash.digest() digest_object = securesystemslib.hash.digest('sha384') digest_object = securesystemslib.hash.digest('sha256', 'hashlib') # The expected interface for digest objects. digest_object.digest_size digest_object.hexdigest() digest_object.update('data') digest_object.digest() # Added hash routines by this module. digest_object = securesystemslib.hash.digest_fileobject(file_object) digest_object = securesystemslib.hash.digest_filename(filename) <Arguments> algorithm: The hash algorithm (e.g., 'md5', 'sha1', 'sha256'). hash_library: The crypto library to use for the given hash algorithm (e.g., 'hashlib'). <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if an unsupported hashing algorithm is specified, or digest could not be generated with given the algorithm. securesystemslib.exceptions.UnsupportedLibraryError, if an unsupported library was requested via 'hash_library'. <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm)).
entailment
def digest_fileobject(file_object, algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY, normalize_line_endings=False): """ <Purpose> Generate a digest object given a file object. The new digest object is updated with the contents of 'file_object' prior to returning the object to the caller. <Arguments> file_object: File object whose contents will be used as the data to update the hash of a digest object to be returned. algorithm: The hash algorithm (e.g., 'md5', 'sha1', 'sha256'). hash_library: The library providing the hash algorithms (e.g., 'hashlib'). normalize_line_endings: (default False) Whether or not to normalize line endings for cross-platform support. Note that this results in ambiguous hashes (e.g. 'abc\n' and 'abc\r\n' will produce the same hash), so be careful to only apply this to text files (not binary), when that equivalence is desirable and cannot result in easily-maliciously-corrupted files producing the same hash as a valid file. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if an unsupported hashing algorithm was specified via 'algorithm'. securesystemslib.exceptions.UnsupportedLibraryError, if an unsupported crypto library was specified via 'hash_library'. <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm)). """ # Are the arguments properly formatted? If not, raise # 'securesystemslib.exceptions.FormatError'. securesystemslib.formats.NAME_SCHEMA.check_match(algorithm) securesystemslib.formats.NAME_SCHEMA.check_match(hash_library) # Digest object returned whose hash will be updated using 'file_object'. # digest() raises: # securesystemslib.exceptions.UnsupportedAlgorithmError # securesystemslib.exceptions.UnsupportedLibraryError digest_object = digest(algorithm, hash_library) # Defensively seek to beginning, as there's no case where we don't # intend to start from the beginning of the file. file_object.seek(0) # Read the contents of the file object in at most 4096-byte chunks. # Update the hash with the data read from each chunk and return after # the entire file is processed. while True: data = file_object.read(DEFAULT_CHUNK_SIZE) if not data: break if normalize_line_endings: while data[-1:] == b'\r': c = file_object.read(1) if not c: break data += c data = ( data # First Windows .replace(b'\r\n', b'\n') # Then Mac .replace(b'\r', b'\n') ) if not isinstance(data, six.binary_type): digest_object.update(data.encode('utf-8')) else: digest_object.update(data) return digest_object
<Purpose> Generate a digest object given a file object. The new digest object is updated with the contents of 'file_object' prior to returning the object to the caller. <Arguments> file_object: File object whose contents will be used as the data to update the hash of a digest object to be returned. algorithm: The hash algorithm (e.g., 'md5', 'sha1', 'sha256'). hash_library: The library providing the hash algorithms (e.g., 'hashlib'). normalize_line_endings: (default False) Whether or not to normalize line endings for cross-platform support. Note that this results in ambiguous hashes (e.g. 'abc\n' and 'abc\r\n' will produce the same hash), so be careful to only apply this to text files (not binary), when that equivalence is desirable and cannot result in easily-maliciously-corrupted files producing the same hash as a valid file. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if an unsupported hashing algorithm was specified via 'algorithm'. securesystemslib.exceptions.UnsupportedLibraryError, if an unsupported crypto library was specified via 'hash_library'. <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm)).
entailment
def digest_filename(filename, algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY, normalize_line_endings=False): """ <Purpose> Generate a digest object, update its hash using a file object specified by filename, and then return it to the caller. <Arguments> filename: The filename belonging to the file object to be used. algorithm: The hash algorithm (e.g., 'md5', 'sha1', 'sha256'). hash_library: The library providing the hash algorithms (e.g., 'hashlib'). normalize_line_endings: Whether or not to normalize line endings for cross-platform support. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if the given 'algorithm' is unsupported. securesystemslib.exceptions.UnsupportedLibraryError, if the given 'hash_library' is unsupported. <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm)). """ # Are the arguments properly formatted? If not, raise # 'securesystemslib.exceptions.FormatError'. securesystemslib.formats.RELPATH_SCHEMA.check_match(filename) securesystemslib.formats.NAME_SCHEMA.check_match(algorithm) securesystemslib.formats.NAME_SCHEMA.check_match(hash_library) digest_object = None # Open 'filename' in read+binary mode. with open(filename, 'rb') as file_object: # Create digest_object and update its hash data from file_object. # digest_fileobject() raises: # securesystemslib.exceptions.UnsupportedAlgorithmError # securesystemslib.exceptions.UnsupportedLibraryError digest_object = digest_fileobject( file_object, algorithm, hash_library, normalize_line_endings) return digest_object
<Purpose> Generate a digest object, update its hash using a file object specified by filename, and then return it to the caller. <Arguments> filename: The filename belonging to the file object to be used. algorithm: The hash algorithm (e.g., 'md5', 'sha1', 'sha256'). hash_library: The library providing the hash algorithms (e.g., 'hashlib'). normalize_line_endings: Whether or not to normalize line endings for cross-platform support. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if the given 'algorithm' is unsupported. securesystemslib.exceptions.UnsupportedLibraryError, if the given 'hash_library' is unsupported. <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm)).
entailment
def get_token_stream(source: str) -> CommonTokenStream: """ Get the antlr token stream. """ lexer = LuaLexer(InputStream(source)) stream = CommonTokenStream(lexer) return stream
Get the antlr token stream.
entailment
def get_evolution_stone(self, slug): """ Returns a Evolution Stone object containing the details about the evolution stone. """ endpoint = '/evolution-stone/' + slug return self.make_request(self.BASE_URL + endpoint)
Returns a Evolution Stone object containing the details about the evolution stone.
entailment
def get_league(self, slug): """ Returns a Pokemon League object containing the details about the league. """ endpoint = '/league/' + slug return self.make_request(self.BASE_URL + endpoint)
Returns a Pokemon League object containing the details about the league.
entailment
def get_pokemon_by_name(self, name): """ Returns an array of Pokemon objects containing all the forms of the Pokemon specified the name of the Pokemon. """ endpoint = '/pokemon/' + str(name) return self.make_request(self.BASE_URL + endpoint)
Returns an array of Pokemon objects containing all the forms of the Pokemon specified the name of the Pokemon.
entailment
def get_pokemon_by_number(self, number): """ Returns an array of Pokemon objects containing all the forms of the Pokemon specified the Pokedex number. """ endpoint = '/pokemon/' + str(number) return self.make_request(self.BASE_URL + endpoint)
Returns an array of Pokemon objects containing all the forms of the Pokemon specified the Pokedex number.
entailment
def generate_rsa_public_and_private(bits=_DEFAULT_RSA_KEY_BITS): """ <Purpose> Generate public and private RSA keys with modulus length 'bits'. The public and private keys returned conform to 'securesystemslib.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ...' or '-----BEGIN RSA PRIVATE KEY----- ...' The public and private keys are returned as strings in PEM format. 'generate_rsa_public_and_private()' enforces a minimum key size of 2048 bits. If 'bits' is unspecified, a 3072-bit RSA key is generated, which is the key size recommended by TUF. >>> public, private = generate_rsa_public_and_private(2048) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(public) True >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(private) True <Arguments> bits: The key size, or key length, of the RSA key. 'bits' must be 2048, or greater. 'bits' defaults to 3072 if not specified. <Exceptions> securesystemslib.exceptions.FormatError, if 'bits' does not contain the correct format. <Side Effects> The RSA keys are generated from pyca/cryptography's rsa.generate_private_key() function. <Returns> A (public, private) tuple containing the RSA keys in PEM format. """ # Does 'bits' have the correct format? # This check will ensure 'bits' conforms to # 'securesystemslib.formats.RSAKEYBITS_SCHEMA'. 'bits' must be an integer # object, with a minimum value of 2048. Raise # 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match(bits) # Generate the public and private RSA keys. The pyca/cryptography 'rsa' # module performs the actual key generation. The 'bits' argument is used, # and a 2048-bit minimum is enforced by # securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match(). private_key = rsa.generate_private_key(public_exponent=65537, key_size=bits, backend=default_backend()) # Extract the public & private halves of the RSA key and generate their # PEM-formatted representations. Return the key pair as a (public, private) # tuple, where each RSA is a string in PEM format. private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) # Need to generate the public pem from the private key before serialization # to PEM. public_key = private_key.public_key() public_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) return public_pem.decode('utf-8'), private_pem.decode('utf-8')
<Purpose> Generate public and private RSA keys with modulus length 'bits'. The public and private keys returned conform to 'securesystemslib.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ...' or '-----BEGIN RSA PRIVATE KEY----- ...' The public and private keys are returned as strings in PEM format. 'generate_rsa_public_and_private()' enforces a minimum key size of 2048 bits. If 'bits' is unspecified, a 3072-bit RSA key is generated, which is the key size recommended by TUF. >>> public, private = generate_rsa_public_and_private(2048) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(public) True >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(private) True <Arguments> bits: The key size, or key length, of the RSA key. 'bits' must be 2048, or greater. 'bits' defaults to 3072 if not specified. <Exceptions> securesystemslib.exceptions.FormatError, if 'bits' does not contain the correct format. <Side Effects> The RSA keys are generated from pyca/cryptography's rsa.generate_private_key() function. <Returns> A (public, private) tuple containing the RSA keys in PEM format.
entailment
def create_rsa_signature(private_key, data, scheme='rsassa-pss-sha256'): """ <Purpose> Generate a 'scheme' signature. The signature, and the signature scheme used, is returned as a (signature, scheme) tuple. The signing process will use 'private_key' to generate the signature of 'data'. RFC3447 - RSASSA-PSS http://www.ietf.org/rfc/rfc3447.txt >>> public, private = generate_rsa_public_and_private(2048) >>> data = 'The quick brown fox jumps over the lazy dog'.encode('utf-8') >>> scheme = 'rsassa-pss-sha256' >>> signature, scheme = create_rsa_signature(private, data, scheme) >>> securesystemslib.formats.NAME_SCHEMA.matches(scheme) True >>> scheme == 'rsassa-pss-sha256' True >>> securesystemslib.formats.PYCACRYPTOSIGNATURE_SCHEMA.matches(signature) True <Arguments> private_key: The private RSA key, a string in PEM format. data: Data (string) used by create_rsa_signature() to generate the signature. scheme: The signature scheme used to generate the signature. <Exceptions> securesystemslib.exceptions.FormatError, if 'private_key' is improperly formatted. ValueError, if 'private_key' is unset. securesystemslib.exceptions.CryptoError, if the signature cannot be generated. <Side Effects> pyca/cryptography's 'RSAPrivateKey.signer()' called to generate the signature. <Returns> A (signature, scheme) tuple, where the signature is a string and the scheme is one of the supported RSA signature schemes. For example: 'rsassa-pss-sha256'. """ # Does the arguments have the correct format? # If not, raise 'securesystemslib.exceptions.FormatError' if any of the # checks fail. securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key) securesystemslib.formats.DATA_SCHEMA.check_match(data) securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme) # Signing 'data' requires a private key. 'rsassa-pss-sha256' is the only # currently supported signature scheme. signature = None # Verify the signature, but only if the private key has been set. The # private key is a NULL string if unset. Although it may be clearer to # explicitly check that 'private_key' is not '', we can/should check for a # value and not compare identities with the 'is' keyword. Up to this point # 'private_key' has variable size and can be an empty string. if len(private_key): # An if-clause isn't strictly needed here, since 'rsasssa-pss-sha256' is # the only currently supported RSA scheme. Nevertheless, include the # conditional statement to accomodate future schemes that might be added. if scheme == 'rsassa-pss-sha256': # Generate an RSSA-PSS signature. Raise # 'securesystemslib.exceptions.CryptoError' for any of the expected # exceptions raised by pyca/cryptography. try: # 'private_key' (in PEM format) must first be converted to a # pyca/cryptography private key object before a signature can be # generated. private_key_object = load_pem_private_key(private_key.encode('utf-8'), password=None, backend=default_backend()) signature = private_key_object.sign( data, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=hashes.SHA256().digest_size), hashes.SHA256()) # If the PEM data could not be decrypted, or if its structure could not # be decoded successfully. except ValueError: raise securesystemslib.exceptions.CryptoError('The private key' ' (in PEM format) could not be deserialized.') # 'TypeError' is raised if a password was given and the private key was # not encrypted, or if the key was encrypted but no password was # supplied. Note: A passphrase or password is not used when generating # 'private_key', since it should not be encrypted. except TypeError: raise securesystemslib.exceptions.CryptoError('The private key was' ' unexpectedly encrypted.') # 'cryptography.exceptions.UnsupportedAlgorithm' is raised if the # serialized key is of a type that is not supported by the backend, or if # the key is encrypted with a symmetric cipher that is not supported by # the backend. except cryptography.exceptions.UnsupportedAlgorithm: #pragma: no cover raise securesystemslib.exceptions.CryptoError('The private key is' ' encrypted with an unsupported algorithm.') # The RSA_SCHEME_SCHEMA.check_match() above should have validated 'scheme'. # This is a defensive check check.. else: #pragma: no cover raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported' ' signature scheme is specified: ' + repr(scheme)) else: raise ValueError('The required private key is unset.') return signature, scheme
<Purpose> Generate a 'scheme' signature. The signature, and the signature scheme used, is returned as a (signature, scheme) tuple. The signing process will use 'private_key' to generate the signature of 'data'. RFC3447 - RSASSA-PSS http://www.ietf.org/rfc/rfc3447.txt >>> public, private = generate_rsa_public_and_private(2048) >>> data = 'The quick brown fox jumps over the lazy dog'.encode('utf-8') >>> scheme = 'rsassa-pss-sha256' >>> signature, scheme = create_rsa_signature(private, data, scheme) >>> securesystemslib.formats.NAME_SCHEMA.matches(scheme) True >>> scheme == 'rsassa-pss-sha256' True >>> securesystemslib.formats.PYCACRYPTOSIGNATURE_SCHEMA.matches(signature) True <Arguments> private_key: The private RSA key, a string in PEM format. data: Data (string) used by create_rsa_signature() to generate the signature. scheme: The signature scheme used to generate the signature. <Exceptions> securesystemslib.exceptions.FormatError, if 'private_key' is improperly formatted. ValueError, if 'private_key' is unset. securesystemslib.exceptions.CryptoError, if the signature cannot be generated. <Side Effects> pyca/cryptography's 'RSAPrivateKey.signer()' called to generate the signature. <Returns> A (signature, scheme) tuple, where the signature is a string and the scheme is one of the supported RSA signature schemes. For example: 'rsassa-pss-sha256'.
entailment
def verify_rsa_signature(signature, signature_scheme, public_key, data): """ <Purpose> Determine whether the corresponding private key of 'public_key' produced 'signature'. verify_signature() will use the public key, signature scheme, and 'data' to complete the verification. >>> public, private = generate_rsa_public_and_private(2048) >>> data = b'The quick brown fox jumps over the lazy dog' >>> scheme = 'rsassa-pss-sha256' >>> signature, scheme = create_rsa_signature(private, data, scheme) >>> verify_rsa_signature(signature, scheme, public, data) True >>> verify_rsa_signature(signature, scheme, public, b'bad_data') False <Arguments> signature: A signature, as a string. This is the signature returned by create_rsa_signature(). signature_scheme: A string that indicates the signature scheme used to generate 'signature'. 'rsassa-pss-sha256' is currently supported. public_key: The RSA public key, a string in PEM format. data: Data used by securesystemslib.keys.create_signature() to generate 'signature'. 'data' (a string) is needed here to verify 'signature'. <Exceptions> securesystemslib.exceptions.FormatError, if 'signature', 'signature_scheme', 'public_key', or 'data' are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if the signature scheme used by 'signature' is not one supported by securesystemslib.keys.create_signature(). securesystemslib.exceptions.CryptoError, if the private key cannot be decoded or its key type is unsupported. <Side Effects> pyca/cryptography's RSAPublicKey.verifier() called to do the actual verification. <Returns> Boolean. True if the signature is valid, False otherwise. """ # Does 'public_key' have the correct format? # This check will ensure 'public_key' conforms to # 'securesystemslib.formats.PEMRSA_SCHEMA'. Raise # 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(public_key) # Does 'signature_scheme' have the correct format? securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(signature_scheme) # Does 'signature' have the correct format? securesystemslib.formats.PYCACRYPTOSIGNATURE_SCHEMA.check_match(signature) # What about 'data'? securesystemslib.formats.DATA_SCHEMA.check_match(data) # Verify whether the private key of 'public_key' produced 'signature'. # Before returning the 'valid_signature' Boolean result, ensure 'RSASSA-PSS' # was used as the signature scheme. valid_signature = False # Verify the RSASSA-PSS signature with pyca/cryptography. try: public_key_object = serialization.load_pem_public_key(public_key.encode('utf-8'), backend=default_backend()) # verify() raises 'cryptography.exceptions.InvalidSignature' if the # signature is invalid. 'salt_length' is set to the digest size of the # hashing algorithm. try: public_key_object.verify(signature, data, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=hashes.SHA256().digest_size), hashes.SHA256()) return True except cryptography.exceptions.InvalidSignature: return False # Raised by load_pem_public_key(). except (ValueError, cryptography.exceptions.UnsupportedAlgorithm) as e: raise securesystemslib.exceptions.CryptoError('The PEM could not be' ' decoded successfully, or contained an unsupported key type: ' + str(e))
<Purpose> Determine whether the corresponding private key of 'public_key' produced 'signature'. verify_signature() will use the public key, signature scheme, and 'data' to complete the verification. >>> public, private = generate_rsa_public_and_private(2048) >>> data = b'The quick brown fox jumps over the lazy dog' >>> scheme = 'rsassa-pss-sha256' >>> signature, scheme = create_rsa_signature(private, data, scheme) >>> verify_rsa_signature(signature, scheme, public, data) True >>> verify_rsa_signature(signature, scheme, public, b'bad_data') False <Arguments> signature: A signature, as a string. This is the signature returned by create_rsa_signature(). signature_scheme: A string that indicates the signature scheme used to generate 'signature'. 'rsassa-pss-sha256' is currently supported. public_key: The RSA public key, a string in PEM format. data: Data used by securesystemslib.keys.create_signature() to generate 'signature'. 'data' (a string) is needed here to verify 'signature'. <Exceptions> securesystemslib.exceptions.FormatError, if 'signature', 'signature_scheme', 'public_key', or 'data' are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if the signature scheme used by 'signature' is not one supported by securesystemslib.keys.create_signature(). securesystemslib.exceptions.CryptoError, if the private key cannot be decoded or its key type is unsupported. <Side Effects> pyca/cryptography's RSAPublicKey.verifier() called to do the actual verification. <Returns> Boolean. True if the signature is valid, False otherwise.
entailment
def create_rsa_encrypted_pem(private_key, passphrase): """ <Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the algorithm may change over time. c.f. cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/ #cryptography.hazmat.primitives.serialization.BestAvailableEncryption >>> public, private = generate_rsa_public_and_private(2048) >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_key: The private key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the RSA key. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if the passed RSA key cannot be deserialized by pyca cryptography. ValueError, if 'private_key' is unset. <Returns> A string in PEM format (TraditionalOpenSSL), where the private RSA key is encrypted. Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'. """ # This check will ensure 'private_key' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key) # Does 'passphrase' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase) # 'private_key' may still be a NULL string after the # 'securesystemslib.formats.PEMRSA_SCHEMA' so we need an additional check if len(private_key): try: private_key = load_pem_private_key(private_key.encode('utf-8'), password=None, backend=default_backend()) except ValueError: raise securesystemslib.exceptions.CryptoError('The private key' ' (in PEM format) could not be deserialized.') else: raise ValueError('The required private key is unset.') encrypted_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption( passphrase.encode('utf-8'))) return encrypted_pem.decode()
<Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the algorithm may change over time. c.f. cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/ #cryptography.hazmat.primitives.serialization.BestAvailableEncryption >>> public, private = generate_rsa_public_and_private(2048) >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_key: The private key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the RSA key. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if the passed RSA key cannot be deserialized by pyca cryptography. ValueError, if 'private_key' is unset. <Returns> A string in PEM format (TraditionalOpenSSL), where the private RSA key is encrypted. Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'.
entailment
def create_rsa_public_and_private_from_pem(pem, passphrase=None): """ <Purpose> Generate public and private RSA keys from an optionally encrypted PEM. The public and private keys returned conform to 'securesystemslib.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ... -----END RSA PUBLIC KEY-----' and '-----BEGIN RSA PRIVATE KEY----- ...-----END RSA PRIVATE KEY-----' The public and private keys are returned as strings in PEM format. In case the private key part of 'pem' is encrypted pyca/cryptography's load_pem_private_key() method is passed passphrase. In the default case here, pyca/cryptography will decrypt with a PBKDF1+MD5 strengthened'passphrase', and 3DES with CBC mode for encryption/decryption. Alternatively, key data may be encrypted with AES-CTR-Mode and the passphrase strengthened with PBKDF2+SHA256, although this method is used only with TUF encrypted key files. >>> public, private = generate_rsa_public_and_private(2048) >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> returned_public, returned_private = \ create_rsa_public_and_private_from_pem(encrypted_pem, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(returned_public) True >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(returned_private) True >>> public == returned_public True >>> private == returned_private True <Arguments> pem: A byte string in PEM format, where the private key can be encrypted. It has the form: '-----BEGIN RSA PRIVATE KEY-----\n Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC ...' passphrase: (optional) The passphrase, or password, to decrypt the private part of the RSA key. 'passphrase' is not directly used as the encryption key, instead it is used to derive a stronger symmetric key. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if the public and private RSA keys cannot be generated from 'pem', or exported in PEM format. <Side Effects> pyca/cryptography's 'serialization.load_pem_private_key()' called to perform the actual conversion from an encrypted RSA private key to PEM format. <Returns> A (public, private) tuple containing the RSA keys in PEM format. """ # Does 'encryped_pem' have the correct format? # This check will ensure 'pem' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem) # If passed, does 'passphrase' have the correct format? if passphrase is not None: securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase) passphrase = passphrase.encode('utf-8') # Generate a pyca/cryptography key object from 'pem'. The generated # pyca/cryptography key contains the required export methods needed to # generate the PEM-formatted representations of the public and private RSA # key. try: private_key = load_pem_private_key(pem.encode('utf-8'), passphrase, backend=default_backend()) # pyca/cryptography's expected exceptions for 'load_pem_private_key()': # ValueError: If the PEM data could not be decrypted. # (possibly because the passphrase is wrong)." # TypeError: If a password was given and the private key was not encrypted. # Or if the key was encrypted but no password was supplied. # UnsupportedAlgorithm: If the private key (or if the key is encrypted with # an unsupported symmetric cipher) is not supported by the backend. except (ValueError, TypeError, cryptography.exceptions.UnsupportedAlgorithm) as e: # Raise 'securesystemslib.exceptions.CryptoError' and pyca/cryptography's # exception message. Avoid propogating pyca/cryptography's exception trace # to avoid revealing sensitive error. raise securesystemslib.exceptions.CryptoError('RSA (public, private) tuple' ' cannot be generated from the encrypted PEM string: ' + str(e)) # Export the public and private halves of the pyca/cryptography RSA key # object. The (public, private) tuple returned contains the public and # private RSA keys in PEM format, as strings. # Extract the public & private halves of the RSA key and generate their # PEM-formatted representations. Return the key pair as a (public, private) # tuple, where each RSA is a string in PEM format. private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) # Need to generate the public key from the private one before serializing # to PEM format. public_key = private_key.public_key() public_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) return public_pem.decode(), private_pem.decode()
<Purpose> Generate public and private RSA keys from an optionally encrypted PEM. The public and private keys returned conform to 'securesystemslib.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ... -----END RSA PUBLIC KEY-----' and '-----BEGIN RSA PRIVATE KEY----- ...-----END RSA PRIVATE KEY-----' The public and private keys are returned as strings in PEM format. In case the private key part of 'pem' is encrypted pyca/cryptography's load_pem_private_key() method is passed passphrase. In the default case here, pyca/cryptography will decrypt with a PBKDF1+MD5 strengthened'passphrase', and 3DES with CBC mode for encryption/decryption. Alternatively, key data may be encrypted with AES-CTR-Mode and the passphrase strengthened with PBKDF2+SHA256, although this method is used only with TUF encrypted key files. >>> public, private = generate_rsa_public_and_private(2048) >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> returned_public, returned_private = \ create_rsa_public_and_private_from_pem(encrypted_pem, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(returned_public) True >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(returned_private) True >>> public == returned_public True >>> private == returned_private True <Arguments> pem: A byte string in PEM format, where the private key can be encrypted. It has the form: '-----BEGIN RSA PRIVATE KEY-----\n Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC ...' passphrase: (optional) The passphrase, or password, to decrypt the private part of the RSA key. 'passphrase' is not directly used as the encryption key, instead it is used to derive a stronger symmetric key. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if the public and private RSA keys cannot be generated from 'pem', or exported in PEM format. <Side Effects> pyca/cryptography's 'serialization.load_pem_private_key()' called to perform the actual conversion from an encrypted RSA private key to PEM format. <Returns> A (public, private) tuple containing the RSA keys in PEM format.
entailment
def encrypt_key(key_object, password): """ <Purpose> Return a string containing 'key_object' in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key() function can be applied to the encrypted string to restore the original key object. 'key_object' is a TUF key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function calls the pyca/cryptography library to perform the encryption and derive a suitable encryption key. Whereas an encrypted PEM file uses the Triple Data Encryption Algorithm (3DES), the Cipher-block chaining (CBC) mode of operation, and the Password Based Key Derivation Function 1 (PBKF1) + MD5 to strengthen 'password', encrypted TUF keys use AES-256-CTR-Mode and passwords strengthened with PBKDF2-HMAC-SHA256 (100K iterations by default, but may be overriden in 'settings.PBKDF2_ITERATIONS' by the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = {'keytype': 'ed25519', \ 'scheme': 'ed25519', \ 'keyid': \ 'd62247f817883f593cf6c66a5a55292488d457bcf638ae03207dbbba9dbe457d', \ 'keyval': {'public': \ '74addb5ad544a4306b34741bc1175a3613a8d7dc69ff64724243efdec0e301ad', \ 'private': \ '1f26964cc8d4f7ee5f3c5da2fbb7ab35811169573ac367b860a537e47789f8c4'}} >>> passphrase = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, passphrase) >>> securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.matches(encrypted_key.encode('utf-8')) True <Arguments> key_object: The TUF key object that should contain the private portion of the ED25519 key. password: The password, or passphrase, to encrypt the private part of the RSA key. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if any of the arguments are improperly formatted or 'key_object' does not contain the private portion of the key. securesystemslib.exceptions.CryptoError, if an Ed25519 key in encrypted TUF format cannot be created. <Side Effects> pyca/Cryptography cryptographic operations called to perform the actual encryption of 'key_object'. 'password' used to derive a suitable encryption key. <Returns> An encrypted string in 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA' format. """ # Do the arguments have the correct format? # Ensure the arguments have the appropriate number of objects and object # types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ANYKEY_SCHEMA.check_match(key_object) # Does 'password' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(password) # Ensure the private portion of the key is included in 'key_object'. if 'private' not in key_object['keyval'] or not key_object['keyval']['private']: raise securesystemslib.exceptions.FormatError('Key object does not contain' ' a private part.') # Derive a key (i.e., an appropriate encryption key and not the # user's password) from the given 'password'. Strengthen 'password' with # PBKDF2-HMAC-SHA256 (100K iterations by default, but may be overriden in # 'settings.PBKDF2_ITERATIONS' by the user). salt, iterations, derived_key = _generate_derived_key(password) # Store the derived key info in a dictionary, the object expected # by the non-public _encrypt() routine. derived_key_information = {'salt': salt, 'iterations': iterations, 'derived_key': derived_key} # Convert the key object to json string format and encrypt it with the # derived key. encrypted_key = _encrypt(json.dumps(key_object), derived_key_information) return encrypted_key
<Purpose> Return a string containing 'key_object' in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key() function can be applied to the encrypted string to restore the original key object. 'key_object' is a TUF key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function calls the pyca/cryptography library to perform the encryption and derive a suitable encryption key. Whereas an encrypted PEM file uses the Triple Data Encryption Algorithm (3DES), the Cipher-block chaining (CBC) mode of operation, and the Password Based Key Derivation Function 1 (PBKF1) + MD5 to strengthen 'password', encrypted TUF keys use AES-256-CTR-Mode and passwords strengthened with PBKDF2-HMAC-SHA256 (100K iterations by default, but may be overriden in 'settings.PBKDF2_ITERATIONS' by the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = {'keytype': 'ed25519', \ 'scheme': 'ed25519', \ 'keyid': \ 'd62247f817883f593cf6c66a5a55292488d457bcf638ae03207dbbba9dbe457d', \ 'keyval': {'public': \ '74addb5ad544a4306b34741bc1175a3613a8d7dc69ff64724243efdec0e301ad', \ 'private': \ '1f26964cc8d4f7ee5f3c5da2fbb7ab35811169573ac367b860a537e47789f8c4'}} >>> passphrase = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, passphrase) >>> securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.matches(encrypted_key.encode('utf-8')) True <Arguments> key_object: The TUF key object that should contain the private portion of the ED25519 key. password: The password, or passphrase, to encrypt the private part of the RSA key. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if any of the arguments are improperly formatted or 'key_object' does not contain the private portion of the key. securesystemslib.exceptions.CryptoError, if an Ed25519 key in encrypted TUF format cannot be created. <Side Effects> pyca/Cryptography cryptographic operations called to perform the actual encryption of 'key_object'. 'password' used to derive a suitable encryption key. <Returns> An encrypted string in 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA' format.
entailment
def decrypt_key(encrypted_key, password): """ <Purpose> Return a string containing 'encrypted_key' in non-encrypted form. The decrypt_key() function can be applied to the encrypted string to restore the original key object, a TUF key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function calls the appropriate cryptography module (i.e., pyca_crypto_keys.py) to perform the decryption. Encrypted TUF keys use AES-256-CTR-Mode and passwords strengthened with PBKDF2-HMAC-SHA256 (100K iterations be default, but may be overriden in 'settings.py' by the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = {'keytype': 'ed25519', \ 'scheme': 'ed25519', \ 'keyid': \ 'd62247f817883f593cf6c66a5a55292488d457bcf638ae03207dbbba9dbe457d', \ 'keyval': {'public': \ '74addb5ad544a4306b34741bc1175a3613a8d7dc69ff64724243efdec0e301ad', \ 'private': \ '1f26964cc8d4f7ee5f3c5da2fbb7ab35811169573ac367b860a537e47789f8c4'}} >>> passphrase = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, passphrase) >>> decrypted_key = decrypt_key(encrypted_key.encode('utf-8'), passphrase) >>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(decrypted_key) True >>> decrypted_key == ed25519_key True <Arguments> encrypted_key: An encrypted TUF key (additional data is also included, such as salt, number of password iterations used for the derived encryption key, etc) of the form 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'. 'encrypted_key' should have been generated with encrypted_key(). password: The password, or passphrase, to encrypt the private part of the RSA key. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if a TUF key cannot be decrypted from 'encrypted_key'. securesystemslib.exceptions.Error, if a valid TUF key object is not found in 'encrypted_key'. <Side Effects> The pyca/cryptography is library called to perform the actual decryption of 'encrypted_key'. The key derivation data stored in 'encrypted_key' is used to re-derive the encryption/decryption key. <Returns> The decrypted key object in 'securesystemslib.formats.ANYKEY_SCHEMA' format. """ # Do the arguments have the correct format? # Ensure the arguments have the appropriate number of objects and object # types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.check_match(encrypted_key) # Does 'password' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(password) # Decrypt 'encrypted_key', using 'password' (and additional key derivation # data like salts and password iterations) to re-derive the decryption key. json_data = _decrypt(encrypted_key, password) # Raise 'securesystemslib.exceptions.Error' if 'json_data' cannot be # deserialized to a valid 'securesystemslib.formats.ANYKEY_SCHEMA' key # object. key_object = securesystemslib.util.load_json_string(json_data.decode()) return key_object
<Purpose> Return a string containing 'encrypted_key' in non-encrypted form. The decrypt_key() function can be applied to the encrypted string to restore the original key object, a TUF key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function calls the appropriate cryptography module (i.e., pyca_crypto_keys.py) to perform the decryption. Encrypted TUF keys use AES-256-CTR-Mode and passwords strengthened with PBKDF2-HMAC-SHA256 (100K iterations be default, but may be overriden in 'settings.py' by the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = {'keytype': 'ed25519', \ 'scheme': 'ed25519', \ 'keyid': \ 'd62247f817883f593cf6c66a5a55292488d457bcf638ae03207dbbba9dbe457d', \ 'keyval': {'public': \ '74addb5ad544a4306b34741bc1175a3613a8d7dc69ff64724243efdec0e301ad', \ 'private': \ '1f26964cc8d4f7ee5f3c5da2fbb7ab35811169573ac367b860a537e47789f8c4'}} >>> passphrase = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, passphrase) >>> decrypted_key = decrypt_key(encrypted_key.encode('utf-8'), passphrase) >>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(decrypted_key) True >>> decrypted_key == ed25519_key True <Arguments> encrypted_key: An encrypted TUF key (additional data is also included, such as salt, number of password iterations used for the derived encryption key, etc) of the form 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'. 'encrypted_key' should have been generated with encrypted_key(). password: The password, or passphrase, to encrypt the private part of the RSA key. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if a TUF key cannot be decrypted from 'encrypted_key'. securesystemslib.exceptions.Error, if a valid TUF key object is not found in 'encrypted_key'. <Side Effects> The pyca/cryptography is library called to perform the actual decryption of 'encrypted_key'. The key derivation data stored in 'encrypted_key' is used to re-derive the encryption/decryption key. <Returns> The decrypted key object in 'securesystemslib.formats.ANYKEY_SCHEMA' format.
entailment
def _generate_derived_key(password, salt=None, iterations=None): """ Generate a derived key by feeding 'password' to the Password-Based Key Derivation Function (PBKDF2). pyca/cryptography's PBKDF2 implementation is used in this module. 'salt' may be specified so that a previous derived key may be regenerated, otherwise '_SALT_SIZE' is used by default. 'iterations' is the number of SHA-256 iterations to perform, otherwise '_PBKDF2_ITERATIONS' is used by default. """ # Use pyca/cryptography's default backend (e.g., openSSL, CommonCrypto, etc.) # The default backend is not fixed and can be changed by pyca/cryptography # over time. backend = default_backend() # If 'salt' and 'iterations' are unspecified, a new derived key is generated. # If specified, a deterministic key is derived according to the given # 'salt' and 'iterrations' values. if salt is None: salt = os.urandom(_SALT_SIZE) if iterations is None: iterations = _PBKDF2_ITERATIONS # Derive an AES key with PBKDF2. The 'length' is the desired key length of # the derived key. pbkdf_object = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=iterations, backend=backend) derived_key = pbkdf_object.derive(password.encode('utf-8')) return salt, iterations, derived_key
Generate a derived key by feeding 'password' to the Password-Based Key Derivation Function (PBKDF2). pyca/cryptography's PBKDF2 implementation is used in this module. 'salt' may be specified so that a previous derived key may be regenerated, otherwise '_SALT_SIZE' is used by default. 'iterations' is the number of SHA-256 iterations to perform, otherwise '_PBKDF2_ITERATIONS' is used by default.
entailment
def _encrypt(key_data, derived_key_information): """ Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm. 'derived_key_information' should contain a key strengthened by PBKDF2. The key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode). The HMAC of the ciphertext is generated to ensure the ciphertext has not been modified. 'key_data' is the JSON string representation of the key. In the case of RSA keys, this format would be 'securesystemslib.formats.RSAKEY_SCHEMA': {'keytype': 'rsa', 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} 'derived_key_information' is a dictionary of the form: {'salt': '...', 'derived_key': '...', 'iterations': '...'} 'securesystemslib.exceptions.CryptoError' raised if the encryption fails. """ # Generate a random Initialization Vector (IV). Follow the provably secure # encrypt-then-MAC approach, which affords the ability to verify ciphertext # without needing to decrypt it and preventing an attacker from feeding the # block cipher malicious data. Modes like GCM provide both encryption and # authentication, whereas CTR only provides encryption. # Generate a random 128-bit IV. Random bits of data is needed for salts and # initialization vectors suitable for the encryption algorithms used in # 'pyca_crypto_keys.py'. iv = os.urandom(16) # Construct an AES-CTR Cipher object with the given key and a randomly # generated IV. symmetric_key = derived_key_information['derived_key'] encryptor = Cipher(algorithms.AES(symmetric_key), modes.CTR(iv), backend=default_backend()).encryptor() # Encrypt the plaintext and get the associated ciphertext. # Do we need to check for any exceptions? ciphertext = encryptor.update(key_data.encode('utf-8')) + encryptor.finalize() # Generate the hmac of the ciphertext to ensure it has not been modified. # The decryption routine may verify a ciphertext without having to perform # a decryption operation. symmetric_key = derived_key_information['derived_key'] salt = derived_key_information['salt'] hmac_object = \ cryptography.hazmat.primitives.hmac.HMAC(symmetric_key, hashes.SHA256(), backend=default_backend()) hmac_object.update(ciphertext) hmac_value = binascii.hexlify(hmac_object.finalize()) # Store the number of PBKDF2 iterations used to derive the symmetric key so # that the decryption routine can regenerate the symmetric key successfully. # The PBKDF2 iterations are allowed to vary for the keys loaded and saved. iterations = derived_key_information['iterations'] # Return the salt, iterations, hmac, initialization vector, and ciphertext # as a single string. These five values are delimited by # '_ENCRYPTION_DELIMITER' to make extraction easier. This delimiter is # arbitrarily chosen and should not occur in the hexadecimal representations # of the fields it is separating. return binascii.hexlify(salt).decode() + _ENCRYPTION_DELIMITER + \ str(iterations) + _ENCRYPTION_DELIMITER + \ hmac_value.decode() + _ENCRYPTION_DELIMITER + \ binascii.hexlify(iv).decode() + _ENCRYPTION_DELIMITER + \ binascii.hexlify(ciphertext).decode()
Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm. 'derived_key_information' should contain a key strengthened by PBKDF2. The key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode). The HMAC of the ciphertext is generated to ensure the ciphertext has not been modified. 'key_data' is the JSON string representation of the key. In the case of RSA keys, this format would be 'securesystemslib.formats.RSAKEY_SCHEMA': {'keytype': 'rsa', 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} 'derived_key_information' is a dictionary of the form: {'salt': '...', 'derived_key': '...', 'iterations': '...'} 'securesystemslib.exceptions.CryptoError' raised if the encryption fails.
entailment
def _decrypt(file_contents, password): """ The corresponding decryption routine for _encrypt(). 'securesystemslib.exceptions.CryptoError' raised if the decryption fails. """ # Extract the salt, iterations, hmac, initialization vector, and ciphertext # from 'file_contents'. These five values are delimited by # '_ENCRYPTION_DELIMITER'. This delimiter is arbitrarily chosen and should # not occur in the hexadecimal representations of the fields it is # separating. Raise 'securesystemslib.exceptions.CryptoError', if # 'file_contents' does not contains the expected data layout. try: salt, iterations, hmac, iv, ciphertext = \ file_contents.split(_ENCRYPTION_DELIMITER) except ValueError: raise securesystemslib.exceptions.CryptoError('Invalid encrypted file.') # Ensure we have the expected raw data for the delimited cryptographic data. salt = binascii.unhexlify(salt.encode('utf-8')) iterations = int(iterations) iv = binascii.unhexlify(iv.encode('utf-8')) ciphertext = binascii.unhexlify(ciphertext.encode('utf-8')) # Generate derived key from 'password'. The salt and iterations are # specified so that the expected derived key is regenerated correctly. # Discard the old "salt" and "iterations" values, as we only need the old # derived key. junk_old_salt, junk_old_iterations, symmetric_key = \ _generate_derived_key(password, salt, iterations) # Verify the hmac to ensure the ciphertext is valid and has not been altered. # See the encryption routine for why we use the encrypt-then-MAC approach. # The decryption routine may verify a ciphertext without having to perform # a decryption operation. generated_hmac_object = \ cryptography.hazmat.primitives.hmac.HMAC(symmetric_key, hashes.SHA256(), backend=default_backend()) generated_hmac_object.update(ciphertext) generated_hmac = binascii.hexlify(generated_hmac_object.finalize()) if not securesystemslib.util.digests_are_equal(generated_hmac.decode(), hmac): raise securesystemslib.exceptions.CryptoError('Decryption failed.') # Construct a Cipher object, with the key and iv. decryptor = Cipher(algorithms.AES(symmetric_key), modes.CTR(iv), backend=default_backend()).decryptor() # Decryption gets us the authenticated plaintext. plaintext = decryptor.update(ciphertext) + decryptor.finalize() return plaintext
The corresponding decryption routine for _encrypt(). 'securesystemslib.exceptions.CryptoError' raised if the decryption fails.
entailment
def create_environment(home_dir, site_packages=True, clear=False, unzip_setuptools=False, use_distribute=False): """ Creates a new environment in ``home_dir``. If ``site_packages`` is true (the default) then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared. """ home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir) py_executable = os.path.abspath(install_python( home_dir, lib_dir, inc_dir, bin_dir, site_packages=site_packages, clear=clear)) install_distutils(lib_dir, home_dir) if use_distribute or os.environ.get('VIRTUALENV_USE_DISTRIBUTE'): install_distribute(py_executable, unzip=unzip_setuptools) else: install_setuptools(py_executable, unzip=unzip_setuptools) install_pip(py_executable) install_activate(home_dir, bin_dir)
Creates a new environment in ``home_dir``. If ``site_packages`` is true (the default) then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared.
entailment
def path_locations(home_dir): """Return the path locations for the environment (where libraries are, where scripts go, etc)""" # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its # prefix arg is broken: http://bugs.python.org/issue3386 if sys.platform == 'win32': # Windows has lots of problems with executables with spaces in # the name; this function will remove them (using the ~1 # format): mkdir(home_dir) if ' ' in home_dir: try: import win32api except ImportError: print 'Error: the path "%s" has a space in it' % home_dir print 'To handle these kinds of paths, the win32api module must be installed:' print ' http://sourceforge.net/projects/pywin32/' sys.exit(3) home_dir = win32api.GetShortPathName(home_dir) lib_dir = join(home_dir, 'Lib') inc_dir = join(home_dir, 'Include') bin_dir = join(home_dir, 'Scripts') elif is_jython: lib_dir = join(home_dir, 'Lib') inc_dir = join(home_dir, 'Include') bin_dir = join(home_dir, 'bin') else: lib_dir = join(home_dir, 'lib', py_version) inc_dir = join(home_dir, 'include', py_version) bin_dir = join(home_dir, 'bin') return home_dir, lib_dir, inc_dir, bin_dir
Return the path locations for the environment (where libraries are, where scripts go, etc)
entailment
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear): """Install just the base environment, no distutils patches etc""" if sys.executable.startswith(bin_dir): print 'Please use the *system* python to run this script' return if clear: rmtree(lib_dir) ## FIXME: why not delete it? ## Maybe it should delete everything with #!/path/to/venv/python in it logger.notify('Not deleting %s', bin_dir) if hasattr(sys, 'real_prefix'): logger.notify('Using real prefix %r' % sys.real_prefix) prefix = sys.real_prefix else: prefix = sys.prefix mkdir(lib_dir) fix_lib64(lib_dir) stdlib_dirs = [os.path.dirname(os.__file__)] if sys.platform == 'win32': stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs')) elif sys.platform == 'darwin': stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages')) for stdlib_dir in stdlib_dirs: if not os.path.isdir(stdlib_dir): continue if hasattr(os, 'symlink'): logger.info('Symlinking Python bootstrap modules') else: logger.info('Copying Python bootstrap modules') logger.indent += 2 try: for fn in os.listdir(stdlib_dir): if fn != 'site-packages' and os.path.splitext(fn)[0] in REQUIRED_MODULES: copyfile(join(stdlib_dir, fn), join(lib_dir, fn)) finally: logger.indent -= 2 mkdir(join(lib_dir, 'site-packages')) writefile(join(lib_dir, 'site.py'), SITE_PY) writefile(join(lib_dir, 'orig-prefix.txt'), prefix) site_packages_filename = join(lib_dir, 'no-global-site-packages.txt') if not site_packages: writefile(site_packages_filename, '') else: if os.path.exists(site_packages_filename): logger.info('Deleting %s' % site_packages_filename) os.unlink(site_packages_filename) stdinc_dir = join(prefix, 'include', py_version) if os.path.exists(stdinc_dir): copyfile(stdinc_dir, inc_dir) else: logger.debug('No include dir %s' % stdinc_dir) if sys.exec_prefix != prefix: if sys.platform == 'win32': exec_dir = join(sys.exec_prefix, 'lib') elif is_jython: exec_dir = join(sys.exec_prefix, 'Lib') else: exec_dir = join(sys.exec_prefix, 'lib', py_version) for fn in os.listdir(exec_dir): copyfile(join(exec_dir, fn), join(lib_dir, fn)) if is_jython: # Jython has either jython-dev.jar and javalib/ dir, or just # jython.jar for name in 'jython-dev.jar', 'javalib', 'jython.jar': src = join(prefix, name) if os.path.exists(src): copyfile(src, join(home_dir, name)) # XXX: registry should always exist after Jython 2.5rc1 src = join(prefix, 'registry') if os.path.exists(src): copyfile(src, join(home_dir, 'registry'), symlink=False) copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'), symlink=False) mkdir(bin_dir) py_executable = join(bin_dir, os.path.basename(sys.executable)) if 'Python.framework' in prefix: if re.search(r'/Python(?:-32|-64)*$', py_executable): # The name of the python executable is not quite what # we want, rename it. py_executable = os.path.join( os.path.dirname(py_executable), 'python') logger.notify('New %s executable in %s', expected_exe, py_executable) if sys.executable != py_executable: ## FIXME: could I just hard link? executable = sys.executable if sys.platform == 'cygwin' and os.path.exists(executable + '.exe'): # Cygwin misreports sys.executable sometimes executable += '.exe' py_executable += '.exe' logger.info('Executable actually exists in %s' % executable) shutil.copyfile(executable, py_executable) make_exe(py_executable) if sys.platform == 'win32' or sys.platform == 'cygwin': pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe') if os.path.exists(pythonw): logger.info('Also created pythonw.exe') shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe')) if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe: secondary_exe = os.path.join(os.path.dirname(py_executable), expected_exe) py_executable_ext = os.path.splitext(py_executable)[1] if py_executable_ext == '.exe': # python2.4 gives an extension of '.4' :P secondary_exe += py_executable_ext if os.path.exists(secondary_exe): logger.warn('Not overwriting existing %s script %s (you must use %s)' % (expected_exe, secondary_exe, py_executable)) else: logger.notify('Also creating executable in %s' % secondary_exe) shutil.copyfile(sys.executable, secondary_exe) make_exe(secondary_exe) if 'Python.framework' in prefix: logger.debug('MacOSX Python framework detected') # Make sure we use the the embedded interpreter inside # the framework, even if sys.executable points to # the stub executable in ${sys.prefix}/bin # See http://groups.google.com/group/python-virtualenv/ # browse_thread/thread/17cab2f85da75951 shutil.copy( os.path.join( prefix, 'Resources/Python.app/Contents/MacOS/%s' % os.path.basename(sys.executable)), py_executable) # Copy the framework's dylib into the virtual # environment virtual_lib = os.path.join(home_dir, '.Python') if os.path.exists(virtual_lib): os.unlink(virtual_lib) copyfile( os.path.join(prefix, 'Python'), virtual_lib) # And then change the install_name of the copied python executable try: call_subprocess( ["install_name_tool", "-change", os.path.join(prefix, 'Python'), '@executable_path/../.Python', py_executable]) except: logger.fatal( "Could not call install_name_tool -- you must have Apple's development tools installed") raise # Some tools depend on pythonX.Y being present py_executable_version = '%s.%s' % ( sys.version_info[0], sys.version_info[1]) if not py_executable.endswith(py_executable_version): # symlinking pythonX.Y > python pth = py_executable + '%s.%s' % ( sys.version_info[0], sys.version_info[1]) if os.path.exists(pth): os.unlink(pth) os.symlink('python', pth) else: # reverse symlinking python -> pythonX.Y (with --python) pth = join(bin_dir, 'python') if os.path.exists(pth): os.unlink(pth) os.symlink(os.path.basename(py_executable), pth) if sys.platform == 'win32' and ' ' in py_executable: # There's a bug with subprocess on Windows when using a first # argument that has a space in it. Instead we have to quote # the value: py_executable = '"%s"' % py_executable cmd = [py_executable, '-c', 'import sys; print sys.prefix'] logger.info('Testing executable with %s %s "%s"' % tuple(cmd)) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) proc_stdout, proc_stderr = proc.communicate() proc_stdout = os.path.normcase(os.path.abspath(proc_stdout.strip())) if proc_stdout != os.path.normcase(os.path.abspath(home_dir)): logger.fatal( 'ERROR: The executable %s is not functioning' % py_executable) logger.fatal( 'ERROR: It thinks sys.prefix is %r (should be %r)' % (proc_stdout, os.path.normcase(os.path.abspath(home_dir)))) logger.fatal( 'ERROR: virtualenv is not compatible with this system or executable') if sys.platform == 'win32': logger.fatal( 'Note: some Windows users have reported this error when they installed Python for "Only this user". The problem may be resolvable if you install Python "For all users". (See https://bugs.launchpad.net/virtualenv/+bug/352844)') sys.exit(100) else: logger.info('Got sys.prefix result: %r' % proc_stdout) pydistutils = os.path.expanduser('~/.pydistutils.cfg') if os.path.exists(pydistutils): logger.notify('Please make sure you remove any previous custom paths from ' 'your %s file.' % pydistutils) ## FIXME: really this should be calculated earlier return py_executable
Install just the base environment, no distutils patches etc
entailment
def fix_lib64(lib_dir): """ Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y instead of lib/pythonX.Y. If this is such a platform we'll just create a symlink so lib64 points to lib """ if [p for p in distutils.sysconfig.get_config_vars().values() if isinstance(p, basestring) and 'lib64' in p]: logger.debug('This system uses lib64; symlinking lib64 to lib') assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], ( "Unexpected python lib dir: %r" % lib_dir) lib_parent = os.path.dirname(lib_dir) assert os.path.basename(lib_parent) == 'lib', ( "Unexpected parent dir: %r" % lib_parent) copyfile(lib_parent, os.path.join(os.path.dirname(lib_parent), 'lib64'))
Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y instead of lib/pythonX.Y. If this is such a platform we'll just create a symlink so lib64 points to lib
entailment
def resolve_interpreter(exe): """ If the executable given isn't an absolute path, search $PATH for the interpreter """ if os.path.abspath(exe) != exe: paths = os.environ.get('PATH', '').split(os.pathsep) for path in paths: if os.path.exists(os.path.join(path, exe)): exe = os.path.join(path, exe) break if not os.path.exists(exe): logger.fatal('The executable %s (from --python=%s) does not exist' % (exe, exe)) sys.exit(3) return exe
If the executable given isn't an absolute path, search $PATH for the interpreter
entailment
def make_environment_relocatable(home_dir): """ Makes the already-existing environment use relative paths, and takes out the #!-based environment selection in scripts. """ activate_this = os.path.join(home_dir, 'bin', 'activate_this.py') if not os.path.exists(activate_this): logger.fatal( 'The environment doesn\'t have a file %s -- please re-run virtualenv ' 'on this environment to update it' % activate_this) fixup_scripts(home_dir) fixup_pth_and_egg_link(home_dir)
Makes the already-existing environment use relative paths, and takes out the #!-based environment selection in scripts.
entailment
def generate_rsa_key(bits=_DEFAULT_RSA_KEY_BITS, scheme='rsassa-pss-sha256'): """ <Purpose> Generate public and private RSA keys, with modulus length 'bits'. In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form: {'keytype': 'rsa', 'scheme': 'rsassa-pss-sha256', 'keyid': keyid, 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} The public and private keys are strings in PEM format. Although the PyCA cryptography library and/or its crypto backend might set a minimum key size, generate() enforces a minimum key size of 2048 bits. If 'bits' is unspecified, a 3072-bit RSA key is generated, which is the key size recommended by securesystemslib. These key size restrictions are only enforced for keys generated within securesystemslib. RSA keys with sizes lower than what we recommended may still be imported (e.g., with import_rsakey_from_pem(). >>> rsa_key = generate_rsa_key(bits=2048) >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key) True >>> public = rsa_key['keyval']['public'] >>> private = rsa_key['keyval']['private'] >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(public) True >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(private) True <Arguments> bits: The key size, or key length, of the RSA key. 'bits' must be 2048, or greater, and a multiple of 256. scheme: The signature scheme used by the key. It must be one of ['rsassa-pss-sha256']. <Exceptions> securesystemslib.exceptions.FormatError, if 'bits' is improperly or invalid (i.e., not an integer and not at least 2048). ValueError, if an exception occurs after calling the RSA key generation routine. The 'ValueError' exception is raised by the key generation function of the cryptography library called. <Side Effects> None. <Returns> A dictionary containing the RSA keys and other identifying information. Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'. """ # Does 'bits' have the correct format? This check will ensure 'bits' # conforms to 'securesystemslib.formats.RSAKEYBITS_SCHEMA'. 'bits' must be # an integer object, with a minimum value of 2048. Raise # 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match(bits) securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme) # Begin building the RSA key dictionary. rsakey_dict = {} keytype = 'rsa' public = None private = None # Generate the public and private RSA keys. The pyca/cryptography module is # used to generate the actual key. Raise 'ValueError' if 'bits' is less than # 1024, although a 2048-bit minimum is enforced by # securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match(). public, private = securesystemslib.pyca_crypto_keys.generate_rsa_public_and_private(bits) # When loading in PEM keys, extract_pem() is called, which strips any # leading or trailing new line characters. Do the same here before generating # the keyid. public = extract_pem(public, private_pem=False) private = extract_pem(private, private_pem=True) # Generate the keyid of the RSA key. Note: The private key material is not # included in the generation of the 'keyid' identifier. Convert any '\r\n' # (e.g., Windows) newline characters to '\n' so that a consistent keyid is # generated. key_value = {'public': public.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) # Build the 'rsakey_dict' dictionary. Update 'key_value' with the RSA # private key prior to adding 'key_value' to 'rsakey_dict'. key_value['private'] = private rsakey_dict['keytype'] = keytype rsakey_dict['scheme'] = scheme rsakey_dict['keyid'] = keyid rsakey_dict['keyid_hash_algorithms'] = securesystemslib.settings.HASH_ALGORITHMS rsakey_dict['keyval'] = key_value return rsakey_dict
<Purpose> Generate public and private RSA keys, with modulus length 'bits'. In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form: {'keytype': 'rsa', 'scheme': 'rsassa-pss-sha256', 'keyid': keyid, 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} The public and private keys are strings in PEM format. Although the PyCA cryptography library and/or its crypto backend might set a minimum key size, generate() enforces a minimum key size of 2048 bits. If 'bits' is unspecified, a 3072-bit RSA key is generated, which is the key size recommended by securesystemslib. These key size restrictions are only enforced for keys generated within securesystemslib. RSA keys with sizes lower than what we recommended may still be imported (e.g., with import_rsakey_from_pem(). >>> rsa_key = generate_rsa_key(bits=2048) >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key) True >>> public = rsa_key['keyval']['public'] >>> private = rsa_key['keyval']['private'] >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(public) True >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(private) True <Arguments> bits: The key size, or key length, of the RSA key. 'bits' must be 2048, or greater, and a multiple of 256. scheme: The signature scheme used by the key. It must be one of ['rsassa-pss-sha256']. <Exceptions> securesystemslib.exceptions.FormatError, if 'bits' is improperly or invalid (i.e., not an integer and not at least 2048). ValueError, if an exception occurs after calling the RSA key generation routine. The 'ValueError' exception is raised by the key generation function of the cryptography library called. <Side Effects> None. <Returns> A dictionary containing the RSA keys and other identifying information. Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
entailment
def generate_ecdsa_key(scheme='ecdsa-sha2-nistp256'): """ <Purpose> Generate public and private ECDSA keys, with NIST P-256 + SHA256 (for hashing) being the default scheme. In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form: {'keytype': 'ecdsa-sha2-nistp256', 'scheme', 'ecdsa-sha2-nistp256', 'keyid': keyid, 'keyval': {'public': '', 'private': ''}} The public and private keys are strings in TODO format. >>> ecdsa_key = generate_ecdsa_key(scheme='ecdsa-sha2-nistp256') >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key) True <Arguments> scheme: The ECDSA signature scheme. By default, ECDSA NIST P-256 is used, with SHA256 for hashing. <Exceptions> securesystemslib.exceptions.FormatError, if 'scheme' is improperly formatted or invalid (i.e., not one of the supported ECDSA signature schemes). <Side Effects> None. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'. """ # Does 'scheme' have the correct format? # This check will ensure 'scheme' is properly formatted and is a supported # ECDSA signature scheme. Raise 'securesystemslib.exceptions.FormatError' if # the check fails. securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme) # Begin building the ECDSA key dictionary. ecdsa_key = {} keytype = 'ecdsa-sha2-nistp256' public = None private = None # Generate the public and private ECDSA keys with one of the supported # libraries. public, private = \ securesystemslib.ecdsa_keys.generate_public_and_private(scheme) # Generate the keyid of the Ed25519 key. 'key_value' corresponds to the # 'keyval' entry of the 'Ed25519KEY_SCHEMA' dictionary. The private key # information is not included in the generation of the 'keyid' identifier. # Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a # consistent keyid is generated. key_value = {'public': public.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) # Build the 'ed25519_key' dictionary. Update 'key_value' with the Ed25519 # private key prior to adding 'key_value' to 'ed25519_key'. key_value['private'] = private ecdsa_key['keytype'] = keytype ecdsa_key['scheme'] = scheme ecdsa_key['keyid'] = keyid ecdsa_key['keyval'] = key_value # Add "keyid_hash_algorithms" so that equal ECDSA keys with different keyids # can be associated using supported keyid_hash_algorithms. ecdsa_key['keyid_hash_algorithms'] = \ securesystemslib.settings.HASH_ALGORITHMS return ecdsa_key
<Purpose> Generate public and private ECDSA keys, with NIST P-256 + SHA256 (for hashing) being the default scheme. In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form: {'keytype': 'ecdsa-sha2-nistp256', 'scheme', 'ecdsa-sha2-nistp256', 'keyid': keyid, 'keyval': {'public': '', 'private': ''}} The public and private keys are strings in TODO format. >>> ecdsa_key = generate_ecdsa_key(scheme='ecdsa-sha2-nistp256') >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key) True <Arguments> scheme: The ECDSA signature scheme. By default, ECDSA NIST P-256 is used, with SHA256 for hashing. <Exceptions> securesystemslib.exceptions.FormatError, if 'scheme' is improperly formatted or invalid (i.e., not one of the supported ECDSA signature schemes). <Side Effects> None. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
entailment
def generate_ed25519_key(scheme='ed25519'): """ <Purpose> Generate public and private ED25519 keys, both of length 32-bytes, although they are hexlified to 64 bytes. In addition, a keyid identifier generated for the returned ED25519 object. The object returned conforms to 'securesystemslib.formats.ED25519KEY_SCHEMA' and has the form: {'keytype': 'ed25519', 'scheme': 'ed25519', 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'keyval': {'public': '9ccf3f02b17f82febf5dd3bab878b767d8408...', 'private': 'ab310eae0e229a0eceee3947b6e0205dfab3...'}} >>> ed25519_key = generate_ed25519_key() >>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(ed25519_key) True >>> len(ed25519_key['keyval']['public']) 64 >>> len(ed25519_key['keyval']['private']) 64 <Arguments> scheme: The signature scheme used by the generated Ed25519 key. <Exceptions> None. <Side Effects> The ED25519 keys are generated by calling either the optimized pure Python implementation of ed25519, or the ed25519 routines provided by 'pynacl'. <Returns> A dictionary containing the ED25519 keys and other identifying information. Conforms to 'securesystemslib.formats.ED25519KEY_SCHEMA'. """ # Are the arguments properly formatted? If not, raise an # 'securesystemslib.exceptions.FormatError' exceptions. securesystemslib.formats.ED25519_SIG_SCHEMA.check_match(scheme) # Begin building the Ed25519 key dictionary. ed25519_key = {} keytype = 'ed25519' public = None private = None # Generate the public and private Ed25519 key with the 'pynacl' library. # Unlike in the verification of Ed25519 signatures, do not fall back to the # optimized, pure python implementation provided by PyCA. Ed25519 should # always be generated with a backend like libsodium to prevent side-channel # attacks. public, private = \ securesystemslib.ed25519_keys.generate_public_and_private() # Generate the keyid of the Ed25519 key. 'key_value' corresponds to the # 'keyval' entry of the 'Ed25519KEY_SCHEMA' dictionary. The private key # information is not included in the generation of the 'keyid' identifier. key_value = {'public': binascii.hexlify(public).decode(), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) # Build the 'ed25519_key' dictionary. Update 'key_value' with the Ed25519 # private key prior to adding 'key_value' to 'ed25519_key'. key_value['private'] = binascii.hexlify(private).decode() ed25519_key['keytype'] = keytype ed25519_key['scheme'] = scheme ed25519_key['keyid'] = keyid ed25519_key['keyid_hash_algorithms'] = securesystemslib.settings.HASH_ALGORITHMS ed25519_key['keyval'] = key_value return ed25519_key
<Purpose> Generate public and private ED25519 keys, both of length 32-bytes, although they are hexlified to 64 bytes. In addition, a keyid identifier generated for the returned ED25519 object. The object returned conforms to 'securesystemslib.formats.ED25519KEY_SCHEMA' and has the form: {'keytype': 'ed25519', 'scheme': 'ed25519', 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'keyval': {'public': '9ccf3f02b17f82febf5dd3bab878b767d8408...', 'private': 'ab310eae0e229a0eceee3947b6e0205dfab3...'}} >>> ed25519_key = generate_ed25519_key() >>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(ed25519_key) True >>> len(ed25519_key['keyval']['public']) 64 >>> len(ed25519_key['keyval']['private']) 64 <Arguments> scheme: The signature scheme used by the generated Ed25519 key. <Exceptions> None. <Side Effects> The ED25519 keys are generated by calling either the optimized pure Python implementation of ed25519, or the ed25519 routines provided by 'pynacl'. <Returns> A dictionary containing the ED25519 keys and other identifying information. Conforms to 'securesystemslib.formats.ED25519KEY_SCHEMA'.
entailment
def format_keyval_to_metadata(keytype, scheme, key_value, private=False): """ <Purpose> Return a dictionary conformant to 'securesystemslib.formats.KEY_SCHEMA'. If 'private' is True, include the private key. The dictionary returned has the form: {'keytype': keytype, 'scheme' : scheme, 'keyval': {'public': '...', 'private': '...'}} or if 'private' is False: {'keytype': keytype, 'scheme': scheme, 'keyval': {'public': '...', 'private': ''}} >>> ed25519_key = generate_ed25519_key() >>> key_val = ed25519_key['keyval'] >>> keytype = ed25519_key['keytype'] >>> scheme = ed25519_key['scheme'] >>> ed25519_metadata = \ format_keyval_to_metadata(keytype, scheme, key_val, private=True) >>> securesystemslib.formats.KEY_SCHEMA.matches(ed25519_metadata) True <Arguments> key_type: The 'rsa' or 'ed25519' strings. scheme: The signature scheme used by the key. key_value: A dictionary containing a private and public keys. 'key_value' is of the form: {'public': '...', 'private': '...'}}, conformant to 'securesystemslib.formats.KEYVAL_SCHEMA'. private: Indicates if the private key should be included in the dictionary returned. <Exceptions> securesystemslib.exceptions.FormatError, if 'key_value' does not conform to 'securesystemslib.formats.KEYVAL_SCHEMA', or if the private key is not present in 'key_value' if requested by the caller via 'private'. <Side Effects> None. <Returns> A 'securesystemslib.formats.KEY_SCHEMA' dictionary. """ # Does 'keytype' have the correct format? # This check will ensure 'keytype' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.KEYTYPE_SCHEMA.check_match(keytype) # Does 'scheme' have the correct format? securesystemslib.formats.SCHEME_SCHEMA.check_match(scheme) # Does 'key_value' have the correct format? securesystemslib.formats.KEYVAL_SCHEMA.check_match(key_value) if private is True: # If the caller requests (via the 'private' argument) to include a private # key in the returned dictionary, ensure the private key is actually # present in 'key_val' (a private key is optional for 'KEYVAL_SCHEMA' # dicts). if 'private' not in key_value: raise securesystemslib.exceptions.FormatError('The required private key' ' is missing from: ' + repr(key_value)) else: return {'keytype': keytype, 'scheme': scheme, 'keyval': key_value} else: public_key_value = {'public': key_value['public']} return {'keytype': keytype, 'scheme': scheme, 'keyid_hash_algorithms': securesystemslib.settings.HASH_ALGORITHMS, 'keyval': public_key_value}
<Purpose> Return a dictionary conformant to 'securesystemslib.formats.KEY_SCHEMA'. If 'private' is True, include the private key. The dictionary returned has the form: {'keytype': keytype, 'scheme' : scheme, 'keyval': {'public': '...', 'private': '...'}} or if 'private' is False: {'keytype': keytype, 'scheme': scheme, 'keyval': {'public': '...', 'private': ''}} >>> ed25519_key = generate_ed25519_key() >>> key_val = ed25519_key['keyval'] >>> keytype = ed25519_key['keytype'] >>> scheme = ed25519_key['scheme'] >>> ed25519_metadata = \ format_keyval_to_metadata(keytype, scheme, key_val, private=True) >>> securesystemslib.formats.KEY_SCHEMA.matches(ed25519_metadata) True <Arguments> key_type: The 'rsa' or 'ed25519' strings. scheme: The signature scheme used by the key. key_value: A dictionary containing a private and public keys. 'key_value' is of the form: {'public': '...', 'private': '...'}}, conformant to 'securesystemslib.formats.KEYVAL_SCHEMA'. private: Indicates if the private key should be included in the dictionary returned. <Exceptions> securesystemslib.exceptions.FormatError, if 'key_value' does not conform to 'securesystemslib.formats.KEYVAL_SCHEMA', or if the private key is not present in 'key_value' if requested by the caller via 'private'. <Side Effects> None. <Returns> A 'securesystemslib.formats.KEY_SCHEMA' dictionary.
entailment
def format_metadata_to_key(key_metadata): """ <Purpose> Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA) according to the keytype of 'key_metadata'. The dict returned by this function has the exact format as the dict returned by one of the key generations functions, like generate_ed25519_key(). The dict returned has the form: {'keytype': keytype, 'scheme': scheme, 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'keyval': {'public': '...', 'private': '...'}} For example, RSA key dictionaries in RSAKEY_SCHEMA format should be used by modules storing a collection of keys, such as with keydb.py. RSA keys as stored in metadata files use a different format, so this function should be called if an RSA key is extracted from one of these metadata files and need converting. The key generation functions create an entirely new key and return it in the format appropriate for 'keydb.py'. >>> ed25519_key = generate_ed25519_key() >>> key_val = ed25519_key['keyval'] >>> keytype = ed25519_key['keytype'] >>> scheme = ed25519_key['scheme'] >>> ed25519_metadata = \ format_keyval_to_metadata(keytype, scheme, key_val, private=True) >>> ed25519_key_2, junk = format_metadata_to_key(ed25519_metadata) >>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(ed25519_key_2) True >>> ed25519_key == ed25519_key_2 True <Arguments> key_metadata: The key dictionary as stored in Metadata files, conforming to 'securesystemslib.formats.KEY_SCHEMA'. It has the form: {'keytype': '...', 'scheme': scheme, 'keyval': {'public': '...', 'private': '...'}} <Exceptions> securesystemslib.exceptions.FormatError, if 'key_metadata' does not conform to 'securesystemslib.formats.KEY_SCHEMA'. <Side Effects> None. <Returns> In the case of an RSA key, a dictionary conformant to 'securesystemslib.formats.RSAKEY_SCHEMA'. """ # Does 'key_metadata' have the correct format? # This check will ensure 'key_metadata' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.KEY_SCHEMA.check_match(key_metadata) # Construct the dictionary to be returned. key_dict = {} keytype = key_metadata['keytype'] scheme = key_metadata['scheme'] key_value = key_metadata['keyval'] # Convert 'key_value' to 'securesystemslib.formats.KEY_SCHEMA' and generate # its hash The hash is in hexdigest form. default_keyid = _get_keyid(keytype, scheme, key_value) keyids = set() keyids.add(default_keyid) for hash_algorithm in securesystemslib.settings.HASH_ALGORITHMS: keyid = _get_keyid(keytype, scheme, key_value, hash_algorithm) keyids.add(keyid) # All the required key values gathered. Build 'key_dict'. # 'keyid_hash_algorithms' key_dict['keytype'] = keytype key_dict['scheme'] = scheme key_dict['keyid'] = default_keyid key_dict['keyid_hash_algorithms'] = securesystemslib.settings.HASH_ALGORITHMS key_dict['keyval'] = key_value return key_dict, keyids
<Purpose> Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA) according to the keytype of 'key_metadata'. The dict returned by this function has the exact format as the dict returned by one of the key generations functions, like generate_ed25519_key(). The dict returned has the form: {'keytype': keytype, 'scheme': scheme, 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'keyval': {'public': '...', 'private': '...'}} For example, RSA key dictionaries in RSAKEY_SCHEMA format should be used by modules storing a collection of keys, such as with keydb.py. RSA keys as stored in metadata files use a different format, so this function should be called if an RSA key is extracted from one of these metadata files and need converting. The key generation functions create an entirely new key and return it in the format appropriate for 'keydb.py'. >>> ed25519_key = generate_ed25519_key() >>> key_val = ed25519_key['keyval'] >>> keytype = ed25519_key['keytype'] >>> scheme = ed25519_key['scheme'] >>> ed25519_metadata = \ format_keyval_to_metadata(keytype, scheme, key_val, private=True) >>> ed25519_key_2, junk = format_metadata_to_key(ed25519_metadata) >>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(ed25519_key_2) True >>> ed25519_key == ed25519_key_2 True <Arguments> key_metadata: The key dictionary as stored in Metadata files, conforming to 'securesystemslib.formats.KEY_SCHEMA'. It has the form: {'keytype': '...', 'scheme': scheme, 'keyval': {'public': '...', 'private': '...'}} <Exceptions> securesystemslib.exceptions.FormatError, if 'key_metadata' does not conform to 'securesystemslib.formats.KEY_SCHEMA'. <Side Effects> None. <Returns> In the case of an RSA key, a dictionary conformant to 'securesystemslib.formats.RSAKEY_SCHEMA'.
entailment
def _get_keyid(keytype, scheme, key_value, hash_algorithm = 'sha256'): """Return the keyid of 'key_value'.""" # 'keyid' will be generated from an object conformant to KEY_SCHEMA, # which is the format Metadata files (e.g., root.json) store keys. # 'format_keyval_to_metadata()' returns the object needed by _get_keyid(). key_meta = format_keyval_to_metadata(keytype, scheme, key_value, private=False) # Convert the key to JSON Canonical format, suitable for adding # to digest objects. key_update_data = securesystemslib.formats.encode_canonical(key_meta) # Create a digest object and call update(), using the JSON # canonical format of 'rskey_meta' as the update data. digest_object = securesystemslib.hash.digest(hash_algorithm) digest_object.update(key_update_data.encode('utf-8')) # 'keyid' becomes the hexadecimal representation of the hash. keyid = digest_object.hexdigest() return keyid
Return the keyid of 'key_value'.
entailment
def create_signature(key_dict, data): """ <Purpose> Return a signature dictionary of the form: {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'sig': '...'}. The signing process will use the private key in key_dict['keyval']['private'] and 'data' to generate the signature. The following signature schemes are supported: 'RSASSA-PSS' RFC3447 - RSASSA-PSS http://www.ietf.org/rfc/rfc3447. 'ed25519' ed25519 - high-speed high security signatures http://ed25519.cr.yp.to/ Which signature to generate is determined by the key type of 'key_dict' and the available cryptography library specified in 'settings'. >>> ed25519_key = generate_ed25519_key() >>> data = 'The quick brown fox jumps over the lazy dog' >>> signature = create_signature(ed25519_key, data) >>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature) True >>> len(signature['sig']) 128 >>> rsa_key = generate_rsa_key(2048) >>> signature = create_signature(rsa_key, data) >>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature) True >>> ecdsa_key = generate_ecdsa_key() >>> signature = create_signature(ecdsa_key, data) >>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature) True <Arguments> key_dict: A dictionary containing the keys. An example RSA key dict has the form: {'keytype': 'rsa', 'scheme': 'rsassa-pss-sha256', 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} The public and private keys are strings in PEM format. data: Data to be signed. This should be a bytes object; data should be encoded/serialized before it is passed here. The same value can be be passed into securesystemslib.verify_signature() (along with the public key) to later verify the signature. <Exceptions> securesystemslib.exceptions.FormatError, if 'key_dict' is improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'key_dict' specifies an unsupported key type or signing scheme. TypeError, if 'key_dict' contains an invalid keytype. <Side Effects> The cryptography library specified in 'settings' is called to perform the actual signing routine. <Returns> A signature dictionary conformant to 'securesystemslib_format.SIGNATURE_SCHEMA'. """ # Does 'key_dict' have the correct format? # This check will ensure 'key_dict' has the appropriate number of objects # and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. # The key type of 'key_dict' must be either 'rsa' or 'ed25519'. securesystemslib.formats.ANYKEY_SCHEMA.check_match(key_dict) # Signing the 'data' object requires a private key. 'rsassa-pss-sha256', # 'ed25519', and 'ecdsa-sha2-nistp256' are the only signing schemes currently # supported. RSASSA-PSS keys and signatures can be generated and verified by # pyca_crypto_keys.py, and Ed25519 keys by PyNaCl and PyCA's optimized, pure # python implementation of Ed25519. signature = {} keytype = key_dict['keytype'] scheme = key_dict['scheme'] public = key_dict['keyval']['public'] private = key_dict['keyval']['private'] keyid = key_dict['keyid'] sig = None if keytype == 'rsa': if scheme == 'rsassa-pss-sha256': private = private.replace('\r\n', '\n') sig, scheme = securesystemslib.pyca_crypto_keys.create_rsa_signature( private, data, scheme) else: raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported' ' RSA signature scheme specified: ' + repr(scheme)) elif keytype == 'ed25519': public = binascii.unhexlify(public.encode('utf-8')) private = binascii.unhexlify(private.encode('utf-8')) sig, scheme = securesystemslib.ed25519_keys.create_signature( public, private, data, scheme) elif keytype == 'ecdsa-sha2-nistp256': sig, scheme = securesystemslib.ecdsa_keys.create_signature( public, private, data, scheme) # 'securesystemslib.formats.ANYKEY_SCHEMA' should have detected invalid key # types. This is a defensive check against an invalid key type. else: # pragma: no cover raise TypeError('Invalid key type.') # Build the signature dictionary to be returned. # The hexadecimal representation of 'sig' is stored in the signature. signature['keyid'] = keyid signature['sig'] = binascii.hexlify(sig).decode() return signature
<Purpose> Return a signature dictionary of the form: {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'sig': '...'}. The signing process will use the private key in key_dict['keyval']['private'] and 'data' to generate the signature. The following signature schemes are supported: 'RSASSA-PSS' RFC3447 - RSASSA-PSS http://www.ietf.org/rfc/rfc3447. 'ed25519' ed25519 - high-speed high security signatures http://ed25519.cr.yp.to/ Which signature to generate is determined by the key type of 'key_dict' and the available cryptography library specified in 'settings'. >>> ed25519_key = generate_ed25519_key() >>> data = 'The quick brown fox jumps over the lazy dog' >>> signature = create_signature(ed25519_key, data) >>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature) True >>> len(signature['sig']) 128 >>> rsa_key = generate_rsa_key(2048) >>> signature = create_signature(rsa_key, data) >>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature) True >>> ecdsa_key = generate_ecdsa_key() >>> signature = create_signature(ecdsa_key, data) >>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature) True <Arguments> key_dict: A dictionary containing the keys. An example RSA key dict has the form: {'keytype': 'rsa', 'scheme': 'rsassa-pss-sha256', 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} The public and private keys are strings in PEM format. data: Data to be signed. This should be a bytes object; data should be encoded/serialized before it is passed here. The same value can be be passed into securesystemslib.verify_signature() (along with the public key) to later verify the signature. <Exceptions> securesystemslib.exceptions.FormatError, if 'key_dict' is improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'key_dict' specifies an unsupported key type or signing scheme. TypeError, if 'key_dict' contains an invalid keytype. <Side Effects> The cryptography library specified in 'settings' is called to perform the actual signing routine. <Returns> A signature dictionary conformant to 'securesystemslib_format.SIGNATURE_SCHEMA'.
entailment
def verify_signature(key_dict, signature, data): """ <Purpose> Determine whether the private key belonging to 'key_dict' produced 'signature'. verify_signature() will use the public key found in 'key_dict', the 'sig' objects contained in 'signature', and 'data' to complete the verification. >>> ed25519_key = generate_ed25519_key() >>> data = 'The quick brown fox jumps over the lazy dog' >>> signature = create_signature(ed25519_key, data) >>> verify_signature(ed25519_key, signature, data) True >>> verify_signature(ed25519_key, signature, 'bad_data') False >>> rsa_key = generate_rsa_key() >>> signature = create_signature(rsa_key, data) >>> verify_signature(rsa_key, signature, data) True >>> verify_signature(rsa_key, signature, 'bad_data') False >>> ecdsa_key = generate_ecdsa_key() >>> signature = create_signature(ecdsa_key, data) >>> verify_signature(ecdsa_key, signature, data) True >>> verify_signature(ecdsa_key, signature, 'bad_data') False <Arguments> key_dict: A dictionary containing the keys and other identifying information. If 'key_dict' is an RSA key, it has the form: {'keytype': 'rsa', 'scheme': 'rsassa-pss-sha256', 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} The public and private keys are strings in PEM format. signature: The signature dictionary produced by one of the key generation functions. 'signature' has the form: {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'sig': sig}. Conformant to 'securesystemslib.formats.SIGNATURE_SCHEMA'. data: Data that the signature is expected to be over. This should be a bytes object; data should be encoded/serialized before it is passed here.) This is the same value that can be passed into securesystemslib.create_signature() in order to create the signature. <Exceptions> securesystemslib.exceptions.FormatError, raised if either 'key_dict' or 'signature' are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'key_dict' or 'signature' specifies an unsupported algorithm. securesystemslib.exceptions.CryptoError, if the KEYID in the given 'key_dict' does not match the KEYID in 'signature'. <Side Effects> The cryptography library specified in 'settings' called to do the actual verification. <Returns> Boolean. True if the signature is valid, False otherwise. """ # Does 'key_dict' have the correct format? # This check will ensure 'key_dict' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ANYKEY_SCHEMA.check_match(key_dict) # Does 'signature' have the correct format? securesystemslib.formats.SIGNATURE_SCHEMA.check_match(signature) # Verify that the KEYID in 'key_dict' matches the KEYID listed in the # 'signature'. if key_dict['keyid'] != signature['keyid']: raise securesystemslib.exceptions.CryptoError('The KEYID (' ' ' + repr(key_dict['keyid']) + ' ) in the given key does not match' ' the KEYID ( ' + repr(signature['keyid']) + ' ) in the signature.') else: logger.debug('The KEYIDs of key_dict and the signature match.') # Using the public key belonging to 'key_dict' # (i.e., rsakey_dict['keyval']['public']), verify whether 'signature' # was produced by key_dict's corresponding private key # key_dict['keyval']['private']. sig = signature['sig'] sig = binascii.unhexlify(sig.encode('utf-8')) public = key_dict['keyval']['public'] keytype = key_dict['keytype'] scheme = key_dict['scheme'] valid_signature = False if keytype == 'rsa': if scheme == 'rsassa-pss-sha256': valid_signature = securesystemslib.pyca_crypto_keys.verify_rsa_signature(sig, scheme, public, data) else: raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported' ' signature scheme is specified: ' + repr(scheme)) elif keytype == 'ed25519': if scheme == 'ed25519': public = binascii.unhexlify(public.encode('utf-8')) valid_signature = securesystemslib.ed25519_keys.verify_signature(public, scheme, sig, data, use_pynacl=USE_PYNACL) else: raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported' ' signature scheme is specified: ' + repr(scheme)) elif keytype == 'ecdsa-sha2-nistp256': if scheme == 'ecdsa-sha2-nistp256': valid_signature = securesystemslib.ecdsa_keys.verify_signature(public, scheme, sig, data) else: raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported' ' signature scheme is specified: ' + repr(scheme)) # 'securesystemslib.formats.ANYKEY_SCHEMA' should have detected invalid key # types. This is a defensive check against an invalid key type. else: # pragma: no cover raise TypeError('Unsupported key type.') return valid_signature
<Purpose> Determine whether the private key belonging to 'key_dict' produced 'signature'. verify_signature() will use the public key found in 'key_dict', the 'sig' objects contained in 'signature', and 'data' to complete the verification. >>> ed25519_key = generate_ed25519_key() >>> data = 'The quick brown fox jumps over the lazy dog' >>> signature = create_signature(ed25519_key, data) >>> verify_signature(ed25519_key, signature, data) True >>> verify_signature(ed25519_key, signature, 'bad_data') False >>> rsa_key = generate_rsa_key() >>> signature = create_signature(rsa_key, data) >>> verify_signature(rsa_key, signature, data) True >>> verify_signature(rsa_key, signature, 'bad_data') False >>> ecdsa_key = generate_ecdsa_key() >>> signature = create_signature(ecdsa_key, data) >>> verify_signature(ecdsa_key, signature, data) True >>> verify_signature(ecdsa_key, signature, 'bad_data') False <Arguments> key_dict: A dictionary containing the keys and other identifying information. If 'key_dict' is an RSA key, it has the form: {'keytype': 'rsa', 'scheme': 'rsassa-pss-sha256', 'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} The public and private keys are strings in PEM format. signature: The signature dictionary produced by one of the key generation functions. 'signature' has the form: {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'sig': sig}. Conformant to 'securesystemslib.formats.SIGNATURE_SCHEMA'. data: Data that the signature is expected to be over. This should be a bytes object; data should be encoded/serialized before it is passed here.) This is the same value that can be passed into securesystemslib.create_signature() in order to create the signature. <Exceptions> securesystemslib.exceptions.FormatError, raised if either 'key_dict' or 'signature' are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'key_dict' or 'signature' specifies an unsupported algorithm. securesystemslib.exceptions.CryptoError, if the KEYID in the given 'key_dict' does not match the KEYID in 'signature'. <Side Effects> The cryptography library specified in 'settings' called to do the actual verification. <Returns> Boolean. True if the signature is valid, False otherwise.
entailment
def import_rsakey_from_private_pem(pem, scheme='rsassa-pss-sha256', password=None): """ <Purpose> Import the private RSA key stored in 'pem', and generate its public key (which will also be included in the returned rsakey object). In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form: {'keytype': 'rsa', 'scheme': 'rsassa-pss-sha256', 'keyid': keyid, 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} The private key is a string in PEM format. >>> rsa_key = generate_rsa_key() >>> scheme = rsa_key['scheme'] >>> private = rsa_key['keyval']['private'] >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> rsa_key2 = import_rsakey_from_private_pem(encrypted_pem, scheme, passphrase) >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key) True >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key2) True <Arguments> pem: A string in PEM format. The private key is extracted and returned in an rsakey object. scheme: The signature scheme used by the imported key. password: (optional) The password, or passphrase, to decrypt the private part of the RSA key if it is encrypted. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'pem' specifies an unsupported key type. <Side Effects> None. <Returns> A dictionary containing the RSA keys and other identifying information. Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'. """ # Does 'pem' have the correct format? # This check will ensure 'pem' conforms to # 'securesystemslib.formats.PEMRSA_SCHEMA'. securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem) # Is 'scheme' properly formatted? securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme) if password is not None: securesystemslib.formats.PASSWORD_SCHEMA.check_match(password) else: logger.debug('The password/passphrase is unset. The PEM is expected' ' to be unencrypted.') # Begin building the RSA key dictionary. rsakey_dict = {} keytype = 'rsa' public = None private = None # Generate the public and private RSA keys. The pyca/cryptography library # performs the actual crypto operations. public, private = \ securesystemslib.pyca_crypto_keys.create_rsa_public_and_private_from_pem( pem, password) public = extract_pem(public, private_pem=False) private = extract_pem(private, private_pem=True) # Generate the keyid of the RSA key. 'key_value' corresponds to the # 'keyval' entry of the 'RSAKEY_SCHEMA' dictionary. The private key # information is not included in the generation of the 'keyid' identifier. # Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a # consistent keyid is generated. key_value = {'public': public.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) # Build the 'rsakey_dict' dictionary. Update 'key_value' with the RSA # private key prior to adding 'key_value' to 'rsakey_dict'. key_value['private'] = private rsakey_dict['keytype'] = keytype rsakey_dict['scheme'] = scheme rsakey_dict['keyid'] = keyid rsakey_dict['keyval'] = key_value return rsakey_dict
<Purpose> Import the private RSA key stored in 'pem', and generate its public key (which will also be included in the returned rsakey object). In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form: {'keytype': 'rsa', 'scheme': 'rsassa-pss-sha256', 'keyid': keyid, 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} The private key is a string in PEM format. >>> rsa_key = generate_rsa_key() >>> scheme = rsa_key['scheme'] >>> private = rsa_key['keyval']['private'] >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> rsa_key2 = import_rsakey_from_private_pem(encrypted_pem, scheme, passphrase) >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key) True >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key2) True <Arguments> pem: A string in PEM format. The private key is extracted and returned in an rsakey object. scheme: The signature scheme used by the imported key. password: (optional) The password, or passphrase, to decrypt the private part of the RSA key if it is encrypted. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'pem' specifies an unsupported key type. <Side Effects> None. <Returns> A dictionary containing the RSA keys and other identifying information. Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
entailment
def import_rsakey_from_public_pem(pem, scheme='rsassa-pss-sha256'): """ <Purpose> Generate an RSA key object from 'pem'. In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form: {'keytype': 'rsa', 'keyid': keyid, 'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...', 'private': ''}} The public portion of the RSA key is a string in PEM format. >>> rsa_key = generate_rsa_key() >>> public = rsa_key['keyval']['public'] >>> rsa_key['keyval']['private'] = '' >>> rsa_key2 = import_rsakey_from_public_pem(public) >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key) True >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key2) True <Arguments> pem: A string in PEM format (it should contain a public RSA key). <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> Only the public portion of the PEM is extracted. Leading or trailing whitespace is not included in the PEM string stored in the rsakey object returned. <Returns> A dictionary containing the RSA keys and other identifying information. Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'. """ # Does 'pem' have the correct format? # This check will ensure arguments has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem) # Does 'scheme' have the correct format? securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme) # Ensure the PEM string has a public header and footer. Although a simple # validation of 'pem' is performed here, a fully valid PEM string is needed # later to successfully verify signatures. Performing stricter validation of # PEMs are left to the external libraries that use 'pem'. if is_pem_public(pem): public_pem = extract_pem(pem, private_pem=False) else: raise securesystemslib.exceptions.FormatError('Invalid public' ' pem: ' + repr(pem)) # Begin building the RSA key dictionary. rsakey_dict = {} keytype = 'rsa' # Generate the keyid of the RSA key. 'key_value' corresponds to the # 'keyval' entry of the 'RSAKEY_SCHEMA' dictionary. The private key # information is not included in the generation of the 'keyid' identifier. # Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a # consistent keyid is generated. key_value = {'public': public_pem.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) rsakey_dict['keytype'] = keytype rsakey_dict['scheme'] = scheme rsakey_dict['keyid'] = keyid rsakey_dict['keyval'] = key_value # Add "keyid_hash_algorithms" so that equal RSA keys with different keyids # can be associated using supported keyid_hash_algorithms. rsakey_dict['keyid_hash_algorithms'] = \ securesystemslib.settings.HASH_ALGORITHMS return rsakey_dict
<Purpose> Generate an RSA key object from 'pem'. In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form: {'keytype': 'rsa', 'keyid': keyid, 'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...', 'private': ''}} The public portion of the RSA key is a string in PEM format. >>> rsa_key = generate_rsa_key() >>> public = rsa_key['keyval']['public'] >>> rsa_key['keyval']['private'] = '' >>> rsa_key2 = import_rsakey_from_public_pem(public) >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key) True >>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key2) True <Arguments> pem: A string in PEM format (it should contain a public RSA key). <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> Only the public portion of the PEM is extracted. Leading or trailing whitespace is not included in the PEM string stored in the rsakey object returned. <Returns> A dictionary containing the RSA keys and other identifying information. Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
entailment
def extract_pem(pem, private_pem=False): """ <Purpose> Extract only the portion of the pem that includes the header and footer, with any leading and trailing characters removed. The string returned has the following form: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' or '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' Note: This function assumes "pem" is a valid pem in the following format: pem header + key material + key footer. Crypto libraries (e.g., pyca's cryptography) that parse the pem returned by this function are expected to fully validate the pem. <Arguments> pem: A string in PEM format. private_pem: Boolean that indicates whether 'pem' is a private PEM. Private PEMs are not shown in exception messages. <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> Only the public and private portion of the PEM is extracted. Leading or trailing whitespace is not included in the returned PEM string. <Returns> A PEM string (excluding leading and trailing newline characters). That is: pem header + key material + pem footer. """ if private_pem: pem_header = '-----BEGIN RSA PRIVATE KEY-----' pem_footer = '-----END RSA PRIVATE KEY-----' else: pem_header = '-----BEGIN PUBLIC KEY-----' pem_footer = '-----END PUBLIC KEY-----' header_start = 0 footer_start = 0 # Raise error message if the expected header or footer is not found in 'pem'. try: header_start = pem.index(pem_header) except ValueError: # Be careful not to print private key material in exception message. if not private_pem: raise securesystemslib.exceptions.FormatError('Required PEM' ' header ' + repr(pem_header) + '\n not found in PEM' ' string: ' + repr(pem)) else: raise securesystemslib.exceptions.FormatError('Required PEM' ' header ' + repr(pem_header) + '\n not found in private PEM string.') try: # Search for 'pem_footer' after the PEM header. footer_start = pem.index(pem_footer, header_start + len(pem_header)) except ValueError: # Be careful not to print private key material in exception message. if not private_pem: raise securesystemslib.exceptions.FormatError('Required PEM' ' footer ' + repr(pem_footer) + '\n not found in PEM' ' string ' + repr(pem)) else: raise securesystemslib.exceptions.FormatError('Required PEM' ' footer ' + repr(pem_footer) + '\n not found in private PEM string.') # Extract only the public portion of 'pem'. Leading or trailing whitespace # is excluded. pem = pem[header_start:footer_start + len(pem_footer)] return pem
<Purpose> Extract only the portion of the pem that includes the header and footer, with any leading and trailing characters removed. The string returned has the following form: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' or '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' Note: This function assumes "pem" is a valid pem in the following format: pem header + key material + key footer. Crypto libraries (e.g., pyca's cryptography) that parse the pem returned by this function are expected to fully validate the pem. <Arguments> pem: A string in PEM format. private_pem: Boolean that indicates whether 'pem' is a private PEM. Private PEMs are not shown in exception messages. <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> Only the public and private portion of the PEM is extracted. Leading or trailing whitespace is not included in the returned PEM string. <Returns> A PEM string (excluding leading and trailing newline characters). That is: pem header + key material + pem footer.
entailment
def encrypt_key(key_object, password): """ <Purpose> Return a string containing 'key_object' in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key() function can be applied to the encrypted string to restore the original key object. 'key_object' is a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function relies on the pyca_crypto_keys.py module to perform the actual encryption. Encrypted keys use AES-256-CTR-Mode, and passwords are strengthened with PBKDF2-HMAC-SHA256 (100K iterations by default, but may be overriden in 'securesystemslib.settings.PBKDF2_ITERATIONS' by the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = generate_ed25519_key() >>> password = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, password).encode('utf-8') >>> securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.matches(encrypted_key) True <Arguments> key_object: A key (containing also the private key portion) of the form 'securesystemslib.formats.ANYKEY_SCHEMA' password: The password, or passphrase, to encrypt the private part of the RSA key. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if 'key_object' cannot be encrypted. <Side Effects> None. <Returns> An encrypted string of the form: 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'. """ # Does 'key_object' have the correct format? # This check will ensure 'key_object' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ANYKEY_SCHEMA.check_match(key_object) # Does 'password' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(password) # Encrypted string of 'key_object'. The encrypted string may be safely saved # to a file and stored offline. encrypted_key = None # Generate an encrypted string of 'key_object' using AES-256-CTR-Mode, where # 'password' is strengthened with PBKDF2-HMAC-SHA256. encrypted_key = securesystemslib.pyca_crypto_keys.encrypt_key(key_object, password) return encrypted_key
<Purpose> Return a string containing 'key_object' in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key() function can be applied to the encrypted string to restore the original key object. 'key_object' is a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function relies on the pyca_crypto_keys.py module to perform the actual encryption. Encrypted keys use AES-256-CTR-Mode, and passwords are strengthened with PBKDF2-HMAC-SHA256 (100K iterations by default, but may be overriden in 'securesystemslib.settings.PBKDF2_ITERATIONS' by the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = generate_ed25519_key() >>> password = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, password).encode('utf-8') >>> securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.matches(encrypted_key) True <Arguments> key_object: A key (containing also the private key portion) of the form 'securesystemslib.formats.ANYKEY_SCHEMA' password: The password, or passphrase, to encrypt the private part of the RSA key. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if 'key_object' cannot be encrypted. <Side Effects> None. <Returns> An encrypted string of the form: 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'.
entailment
def decrypt_key(encrypted_key, passphrase): """ <Purpose> Return a string containing 'encrypted_key' in non-encrypted form. The decrypt_key() function can be applied to the encrypted string to restore the original key object, a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function calls pyca_crypto_keys.py to perform the actual decryption. Encrypted keys use AES-256-CTR-Mode and passwords are strengthened with PBKDF2-HMAC-SHA256 (100K iterations be default, but may be overriden in 'settings.py' by the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = generate_ed25519_key() >>> password = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, password) >>> decrypted_key = decrypt_key(encrypted_key.encode('utf-8'), password) >>> securesystemslib.formats.ANYKEY_SCHEMA.matches(decrypted_key) True >>> decrypted_key == ed25519_key True <Arguments> encrypted_key: An encrypted key (additional data is also included, such as salt, number of password iterations used for the derived encryption key, etc) of the form 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'. 'encrypted_key' should have been generated with encrypt_key(). password: The password, or passphrase, to decrypt 'encrypted_key'. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. The supported general-purpose module takes care of re-deriving the encryption key. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if 'encrypted_key' cannot be decrypted. <Side Effects> None. <Returns> A key object of the form: 'securesystemslib.formats.ANYKEY_SCHEMA' (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). """ # Does 'encrypted_key' have the correct format? # This check ensures 'encrypted_key' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.check_match(encrypted_key) # Does 'passphrase' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase) # Store and return the decrypted key object. key_object = None # Decrypt 'encrypted_key' so that the original key object is restored. # encrypt_key() generates an encrypted string of the key object using # AES-256-CTR-Mode, where 'password' is strengthened with PBKDF2-HMAC-SHA256. key_object = \ securesystemslib.pyca_crypto_keys.decrypt_key(encrypted_key, passphrase) # The corresponding encrypt_key() encrypts and stores key objects in # non-metadata format (i.e., original format of key object argument to # encrypt_key()) prior to returning. return key_object
<Purpose> Return a string containing 'encrypted_key' in non-encrypted form. The decrypt_key() function can be applied to the encrypted string to restore the original key object, a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function calls pyca_crypto_keys.py to perform the actual decryption. Encrypted keys use AES-256-CTR-Mode and passwords are strengthened with PBKDF2-HMAC-SHA256 (100K iterations be default, but may be overriden in 'settings.py' by the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = generate_ed25519_key() >>> password = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, password) >>> decrypted_key = decrypt_key(encrypted_key.encode('utf-8'), password) >>> securesystemslib.formats.ANYKEY_SCHEMA.matches(decrypted_key) True >>> decrypted_key == ed25519_key True <Arguments> encrypted_key: An encrypted key (additional data is also included, such as salt, number of password iterations used for the derived encryption key, etc) of the form 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'. 'encrypted_key' should have been generated with encrypt_key(). password: The password, or passphrase, to decrypt 'encrypted_key'. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. The supported general-purpose module takes care of re-deriving the encryption key. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if 'encrypted_key' cannot be decrypted. <Side Effects> None. <Returns> A key object of the form: 'securesystemslib.formats.ANYKEY_SCHEMA' (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA).
entailment
def create_rsa_encrypted_pem(private_key, passphrase): """ <Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the algorithm may change over time. c.f. cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/ #cryptography.hazmat.primitives.serialization.BestAvailableEncryption >>> rsa_key = generate_rsa_key() >>> private = rsa_key['keyval']['private'] >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_key: The private key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the RSA key. 'passphrase' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if an RSA key in encrypted PEM format cannot be created. TypeError, 'private_key' is unset. <Side Effects> None. <Returns> A string in PEM format, where the private RSA key is encrypted. Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'. """ # Does 'private_key' have the correct format? # This check will ensure 'private_key' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key) # Does 'passphrase' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase) encrypted_pem = None # Generate the public and private RSA keys. A 2048-bit minimum is enforced by # create_rsa_encrypted_pem() via a # securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match(). encrypted_pem = securesystemslib.pyca_crypto_keys.create_rsa_encrypted_pem( private_key, passphrase) return encrypted_pem
<Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the algorithm may change over time. c.f. cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/ #cryptography.hazmat.primitives.serialization.BestAvailableEncryption >>> rsa_key = generate_rsa_key() >>> private = rsa_key['keyval']['private'] >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_key: The private key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the RSA key. 'passphrase' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if an RSA key in encrypted PEM format cannot be created. TypeError, 'private_key' is unset. <Side Effects> None. <Returns> A string in PEM format, where the private RSA key is encrypted. Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'.
entailment
def is_pem_public(pem): """ <Purpose> Checks if a passed PEM formatted string is a PUBLIC key, by looking for the following pattern: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' >>> rsa_key = generate_rsa_key() >>> public = rsa_key['keyval']['public'] >>> private = rsa_key['keyval']['private'] >>> is_pem_public(public) True >>> is_pem_public(private) False <Arguments> pem: A string in PEM format. <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> None <Returns> True if 'pem' is public and false otherwise. """ # Do the arguments have the correct format? # This check will ensure arguments have the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem) pem_header = '-----BEGIN PUBLIC KEY-----' pem_footer = '-----END PUBLIC KEY-----' try: header_start = pem.index(pem_header) pem.index(pem_footer, header_start + len(pem_header)) except ValueError: return False return True
<Purpose> Checks if a passed PEM formatted string is a PUBLIC key, by looking for the following pattern: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' >>> rsa_key = generate_rsa_key() >>> public = rsa_key['keyval']['public'] >>> private = rsa_key['keyval']['private'] >>> is_pem_public(public) True >>> is_pem_public(private) False <Arguments> pem: A string in PEM format. <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> None <Returns> True if 'pem' is public and false otherwise.
entailment
def is_pem_private(pem, keytype='rsa'): """ <Purpose> Checks if a passed PEM formatted string is a PRIVATE key, by looking for the following patterns: '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----' >>> rsa_key = generate_rsa_key() >>> private = rsa_key['keyval']['private'] >>> public = rsa_key['keyval']['public'] >>> is_pem_private(private) True >>> is_pem_private(public) False <Arguments> pem: A string in PEM format. <Exceptions> securesystemslib.exceptions.FormatError, if any of the arguments are improperly formatted. <Side Effects> None <Returns> True if 'pem' is private and false otherwise. """ # Do the arguments have the correct format? # This check will ensure arguments have the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem) securesystemslib.formats.NAME_SCHEMA.check_match(keytype) if keytype == 'rsa': pem_header = '-----BEGIN RSA PRIVATE KEY-----' pem_footer = '-----END RSA PRIVATE KEY-----' elif keytype == 'ec': pem_header = '-----BEGIN EC PRIVATE KEY-----' pem_footer = '-----END EC PRIVATE KEY-----' else: raise securesystemslib.exceptions.FormatError('Unsupported key' ' type: ' + repr(keytype) + '. Supported keytypes: ["rsa", "ec"]') try: header_start = pem.index(pem_header) pem.index(pem_footer, header_start + len(pem_header)) except ValueError: return False return True
<Purpose> Checks if a passed PEM formatted string is a PRIVATE key, by looking for the following patterns: '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----' >>> rsa_key = generate_rsa_key() >>> private = rsa_key['keyval']['private'] >>> public = rsa_key['keyval']['public'] >>> is_pem_private(private) True >>> is_pem_private(public) False <Arguments> pem: A string in PEM format. <Exceptions> securesystemslib.exceptions.FormatError, if any of the arguments are improperly formatted. <Side Effects> None <Returns> True if 'pem' is private and false otherwise.
entailment
def import_ecdsakey_from_private_pem(pem, scheme='ecdsa-sha2-nistp256', password=None): """ <Purpose> Import the private ECDSA key stored in 'pem', and generate its public key (which will also be included in the returned ECDSA key object). In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to: {'keytype': 'ecdsa-sha2-nistp256', 'scheme': 'ecdsa-sha2-nistp256', 'keyid': keyid, 'keyval': {'public': '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----', 'private': '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----'}} The private key is a string in PEM format. >>> ecdsa_key = generate_ecdsa_key() >>> private_pem = ecdsa_key['keyval']['private'] >>> ecdsa_key = import_ecdsakey_from_private_pem(private_pem) >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key) True <Arguments> pem: A string in PEM format. The private key is extracted and returned in an ecdsakey object. scheme: The signature scheme used by the imported key. password: (optional) The password, or passphrase, to decrypt the private part of the ECDSA key if it is encrypted. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'pem' specifies an unsupported key type. <Side Effects> None. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'. """ # Does 'pem' have the correct format? # This check will ensure 'pem' conforms to # 'securesystemslib.formats.ECDSARSA_SCHEMA'. securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem) # Is 'scheme' properly formatted? securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme) if password is not None: securesystemslib.formats.PASSWORD_SCHEMA.check_match(password) else: logger.debug('The password/passphrase is unset. The PEM is expected' ' to be unencrypted.') # Begin building the ECDSA key dictionary. ecdsakey_dict = {} keytype = 'ecdsa-sha2-nistp256' public = None private = None public, private = \ securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem(pem, password) # Generate the keyid of the ECDSA key. 'key_value' corresponds to the # 'keyval' entry of the 'ECDSAKEY_SCHEMA' dictionary. The private key # information is not included in the generation of the 'keyid' identifier. # Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a # consistent keyid is generated. key_value = {'public': public.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) # Build the 'ecdsakey_dict' dictionary. Update 'key_value' with the ECDSA # private key prior to adding 'key_value' to 'ecdsakey_dict'. key_value['private'] = private ecdsakey_dict['keytype'] = keytype ecdsakey_dict['scheme'] = scheme ecdsakey_dict['keyid'] = keyid ecdsakey_dict['keyval'] = key_value # Add "keyid_hash_algorithms" so equal ECDSA keys with # different keyids can be associated using supported keyid_hash_algorithms ecdsakey_dict['keyid_hash_algorithms'] = \ securesystemslib.settings.HASH_ALGORITHMS return ecdsakey_dict
<Purpose> Import the private ECDSA key stored in 'pem', and generate its public key (which will also be included in the returned ECDSA key object). In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to: {'keytype': 'ecdsa-sha2-nistp256', 'scheme': 'ecdsa-sha2-nistp256', 'keyid': keyid, 'keyval': {'public': '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----', 'private': '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----'}} The private key is a string in PEM format. >>> ecdsa_key = generate_ecdsa_key() >>> private_pem = ecdsa_key['keyval']['private'] >>> ecdsa_key = import_ecdsakey_from_private_pem(private_pem) >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key) True <Arguments> pem: A string in PEM format. The private key is extracted and returned in an ecdsakey object. scheme: The signature scheme used by the imported key. password: (optional) The password, or passphrase, to decrypt the private part of the ECDSA key if it is encrypted. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'pem' specifies an unsupported key type. <Side Effects> None. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
entailment
def import_ecdsakey_from_public_pem(pem, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Generate an ECDSA key object from 'pem'. In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form: {'keytype': 'ecdsa-sha2-nistp256', 'scheme': 'ecdsa-sha2-nistp256', 'keyid': keyid, 'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...', 'private': ''}} The public portion of the ECDSA key is a string in PEM format. >>> ecdsa_key = generate_ecdsa_key() >>> public = ecdsa_key['keyval']['public'] >>> ecdsa_key['keyval']['private'] = '' >>> scheme = ecdsa_key['scheme'] >>> ecdsa_key2 = import_ecdsakey_from_public_pem(public, scheme) >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key) True >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key2) True <Arguments> pem: A string in PEM format (it should contain a public ECDSA key). scheme: The signature scheme used by the imported key. <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> Only the public portion of the PEM is extracted. Leading or trailing whitespace is not included in the PEM string stored in the rsakey object returned. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'. """ # Does 'pem' have the correct format? # This check will ensure arguments has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem) # Is 'scheme' properly formatted? securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme) # Ensure the PEM string has a public header and footer. Although a simple # validation of 'pem' is performed here, a fully valid PEM string is needed # later to successfully verify signatures. Performing stricter validation of # PEMs are left to the external libraries that use 'pem'. if is_pem_public(pem): public_pem = extract_pem(pem, private_pem=False) else: raise securesystemslib.exceptions.FormatError('Invalid public' ' pem: ' + repr(pem)) # Begin building the ECDSA key dictionary. ecdsakey_dict = {} keytype = 'ecdsa-sha2-nistp256' # Generate the keyid of the ECDSA key. 'key_value' corresponds to the # 'keyval' entry of the 'ECDSAKEY_SCHEMA' dictionary. The private key # information is not included in the generation of the 'keyid' identifier. # Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a # consistent keyid is generated. key_value = {'public': public_pem.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) ecdsakey_dict['keytype'] = keytype ecdsakey_dict['scheme'] = scheme ecdsakey_dict['keyid'] = keyid ecdsakey_dict['keyval'] = key_value # Add "keyid_hash_algorithms" so that equal ECDSA keys with different keyids # can be associated using supported keyid_hash_algorithms. ecdsakey_dict['keyid_hash_algorithms'] = \ securesystemslib.settings.HASH_ALGORITHMS return ecdsakey_dict
<Purpose> Generate an ECDSA key object from 'pem'. In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form: {'keytype': 'ecdsa-sha2-nistp256', 'scheme': 'ecdsa-sha2-nistp256', 'keyid': keyid, 'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...', 'private': ''}} The public portion of the ECDSA key is a string in PEM format. >>> ecdsa_key = generate_ecdsa_key() >>> public = ecdsa_key['keyval']['public'] >>> ecdsa_key['keyval']['private'] = '' >>> scheme = ecdsa_key['scheme'] >>> ecdsa_key2 = import_ecdsakey_from_public_pem(public, scheme) >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key) True >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key2) True <Arguments> pem: A string in PEM format (it should contain a public ECDSA key). scheme: The signature scheme used by the imported key. <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> Only the public portion of the PEM is extracted. Leading or trailing whitespace is not included in the PEM string stored in the rsakey object returned. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
entailment
def import_ecdsakey_from_pem(pem, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Import either a public or private ECDSA PEM. In contrast to the other explicit import functions (import_ecdsakey_from_public_pem and import_ecdsakey_from_private_pem), this function is useful for when it is not known whether 'pem' is private or public. <Arguments> pem: A string in PEM format. scheme: The signature scheme used by the imported key. <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> None. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'. """ # Does 'pem' have the correct format? # This check will ensure arguments has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem) # Is 'scheme' properly formatted? securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme) public_pem = '' private_pem = '' # Ensure the PEM string has a public or private header and footer. Although # a simple validation of 'pem' is performed here, a fully valid PEM string is # needed later to successfully verify signatures. Performing stricter # validation of PEMs are left to the external libraries that use 'pem'. if is_pem_public(pem): public_pem = extract_pem(pem, private_pem=False) elif is_pem_private(pem, 'ec'): # Return an ecdsakey object (ECDSAKEY_SCHEMA) with the private key included. return import_ecdsakey_from_private_pem(pem, password=None) else: raise securesystemslib.exceptions.FormatError('PEM contains neither a public' ' nor private key: ' + repr(pem)) # Begin building the ECDSA key dictionary. ecdsakey_dict = {} keytype = 'ecdsa-sha2-nistp256' # Generate the keyid of the ECDSA key. 'key_value' corresponds to the # 'keyval' entry of the 'ECDSAKEY_SCHEMA' dictionary. The private key # information is not included in the generation of the 'keyid' identifier. # If a PEM is found to contain a private key, the generated rsakey object # should be returned above. The following key object is for the case of a # PEM with only a public key. Convert any '\r\n' (e.g., Windows) newline # characters to '\n' so that a consistent keyid is generated. key_value = {'public': public_pem.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) ecdsakey_dict['keytype'] = keytype ecdsakey_dict['scheme'] = scheme ecdsakey_dict['keyid'] = keyid ecdsakey_dict['keyval'] = key_value return ecdsakey_dict
<Purpose> Import either a public or private ECDSA PEM. In contrast to the other explicit import functions (import_ecdsakey_from_public_pem and import_ecdsakey_from_private_pem), this function is useful for when it is not known whether 'pem' is private or public. <Arguments> pem: A string in PEM format. scheme: The signature scheme used by the imported key. <Exceptions> securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted. <Side Effects> None. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
entailment
def parse_func_body(self): """If success, return a tuple (args, body)""" self.save() self._expected = [] if self.next_is_rc(Tokens.OPAR, False): # do not render right hidden self.handle_hidden_right() # render hidden after new level args = self.parse_param_list() if args is not None: # may be an empty table if self.next_is_rc(Tokens.CPAR, False): # do not render right hidden self.handle_hidden_right() # render hidden after new level body = self.parse_block() if body: self._expected = [] token = self.next_is_rc(Tokens.END, False) if token: body.stop_char = token.stop self.success() return args, body else: self.abort() else: self.abort() return self.failure()
If success, return a tuple (args, body)
entailment
def get_concrete_class(cls, class_name): """This method provides easier access to all writers inheriting Writer class :param class_name: name of the parser (name of the parser class which should be used) :type class_name: str :return: Writer subclass specified by parser_name :rtype: Writer subclass :raise ValueError: """ def recurrent_class_lookup(cls): for cls in cls.__subclasses__(): if lower(cls.__name__) == lower(class_name): return cls elif len(cls.__subclasses__()) > 0: r = recurrent_class_lookup(cls) if r is not None: return r return None cls = recurrent_class_lookup(cls) if cls: return cls else: raise ValueError("'class_name '%s' is invalid" % class_name)
This method provides easier access to all writers inheriting Writer class :param class_name: name of the parser (name of the parser class which should be used) :type class_name: str :return: Writer subclass specified by parser_name :rtype: Writer subclass :raise ValueError:
entailment
def GetPupil(self): """Retrieve pupil data """ pupil_data = _co.namedtuple('pupil_data', ['ZemaxApertureType', 'ApertureValue', 'entrancePupilDiameter', 'entrancePupilPosition', 'exitPupilDiameter', 'exitPupilPosition', 'ApodizationType', 'ApodizationFactor']) data = self._ilensdataeditor.GetPupil() return pupil_data(*data)
Retrieve pupil data
entailment
def ping(self, targets=list(), filename=str(), status=str()): """ Attempt to ping a list of hosts or networks (can be a single host) :param targets: List - Name(s) or IP(s) of the host(s). :param filename: String - name of the file containing hosts to ping :param status: String - if one of ['alive', 'dead', 'noip'] then only return results that have that status. If this is not specified, then all results will be returned. :return: Type and results depends on whether status is specified: if status == '': return dict: {targets: results} if status != '': return list: targets if targets == status """ if targets and filename: raise SyntaxError("You must specify only one of either targets=[] " "or filename=''.") elif not targets and not filename: raise SyntaxError("You must specify either a list of targets or " "filename='', but not both.") elif filename: targets = self.read_file(filename) my_targets = {'hosts': [], 'nets': []} addresses = [] # Check for valid networks and add hosts and nets to my_targets for target in targets: # Targets may include networks in the format "network mask", or, # a file could contain multiple hosts or IP's on a single line. if len(target.split()) > 1: target_items = target.split() for item in target_items: try: ip = IPAddress(item) # If it is an IPv4 address or mask put in in addresses if ip.version == 4: addresses.append(str(ip)) except AddrFormatError: # IP Address not detected, so assume it's a host name my_targets['hosts'].append(item) except ValueError: # CIDR network detected net = IPNetwork(item) # Make sure it is a CIDR address acceptable to fping if net.ip.is_unicast() and net.version == 4 and \ net.netmask.netmask_bits() in range(8, 31): my_targets['nets'].append(target_items[0]) else: msg = str(str(net) + ':Only IPv4 unicast addresses' ' with bit masks\n ' ' from 8 to 30 are supported.') raise AttributeError(msg) # Iterate over the IP strings in addresses while len(addresses) > 1: ip = IPAddress(addresses[0]) mask = IPAddress(addresses[1]) # Test to see if IP is unicast, and mask is an actual mask if ip.is_unicast() and mask.is_netmask(): net = IPNetwork(str(ip) + '/' + str( mask.netmask_bits())) # Convert ip and mask to CIDR and remove from addresses my_targets['nets'].append(str(net.cidr)) addresses.pop(0) addresses.pop(0) elif ip.is_unicast() and not ip.is_netmask(): # mask was not a mask so only remove IP and start over my_targets['hosts'].append(str(ip)) addresses.pop(0) # There could be one more item in addresses, so check it if addresses: ip = IPAddress(addresses[0]) if ip.is_unicast() and not ip.is_netmask(): my_targets['hosts'].append(addresses[0]) addresses.pop() # target has only one item, so check it else: try: ip = IPAddress(target) if ip.version == 4 and ip.is_unicast() and \ not ip.is_netmask(): my_targets['hosts'].append(target) else: msg = str(target + 'Only IPv4 unicast addresses are ' 'supported.') raise AttributeError(msg) except AddrFormatError: # IP Address not detected, so assume it's a host name my_targets['hosts'].append(target) except ValueError: # CIDR network detected net = IPNetwork(target) if net.ip.is_unicast() and net.version == 4 and \ net.netmask.netmask_bits() in range(8, 31): my_targets['nets'].append(target) else: msg = str(str(net) + ':Only IPv4 unicast addresses' ' with bit masks\n ' ' from 8 to 30 are supported.') raise AttributeError(msg) """ Build the list of commands to run. """ commands = [] if len(my_targets['hosts']) != 0: for target in range(len(my_targets['hosts'])): commands.append([self.fping, '-nV', my_targets['hosts'][ target]]) if len(my_targets['nets']) != 0: for target in range(len(my_targets['nets'])): commands.append([self.fping, '-ngV', my_targets['nets'][ target]]) """ Start pinging each item in my_targets and return the requested results when done. """ pool = ThreadPool(self.num_pools) raw_results = pool.map(self.get_results, commands) pool.close() pool.join() self.results = {host: result for host, result in csv.reader( ''.join(raw_results).splitlines())} if not status: return self.results elif status == 'alive': return self.alive elif status == 'dead': return self.dead elif status == 'noip': return self.noip else: raise SyntaxError("Valid status options are 'alive', 'dead' or " "'noip'")
Attempt to ping a list of hosts or networks (can be a single host) :param targets: List - Name(s) or IP(s) of the host(s). :param filename: String - name of the file containing hosts to ping :param status: String - if one of ['alive', 'dead', 'noip'] then only return results that have that status. If this is not specified, then all results will be returned. :return: Type and results depends on whether status is specified: if status == '': return dict: {targets: results} if status != '': return list: targets if targets == status
entailment
def get_results(cmd): """ def get_results(cmd: list) -> str: return lines Get the ping results using fping. :param cmd: List - the fping command and its options :return: String - raw string output containing csv fping results including the newline characters """ try: return subprocess.check_output(cmd) except subprocess.CalledProcessError as e: return e.output
def get_results(cmd: list) -> str: return lines Get the ping results using fping. :param cmd: List - the fping command and its options :return: String - raw string output containing csv fping results including the newline characters
entailment
def read_file(filename): """ Reads the lines of a file into a list, and returns the list :param filename: String - path and name of the file :return: List - lines within the file """ lines = [] with open(filename) as f: for line in f: if len(line.strip()) != 0: lines.append(line.strip()) return lines
Reads the lines of a file into a list, and returns the list :param filename: String - path and name of the file :return: List - lines within the file
entailment
def _prepare_outputs(self, data_out, outputs): """ Open a ROOT file with option 'RECREATE' to create a new file (the file will be overwritten if it already exists), and using the ZLIB compression algorithm (with compression level 1) for better compatibility with older ROOT versions (see https://root.cern.ch/doc/v614/release-notes.html#important-notice ). :param data_out: :param outputs: :return: """ compress = ROOTModule.ROOT.CompressionSettings(ROOTModule.ROOT.kZLIB, 1) if isinstance(data_out, (str, unicode)): self.file_emulation = True outputs.append(ROOTModule.TFile.Open(data_out, 'RECREATE', '', compress)) # multiple tables - require directory elif isinstance(data_out, ROOTModule.TFile): outputs.append(data_out) else: # assume it's a file like object self.file_emulation = True filename = os.path.join(tempfile.mkdtemp(),'tmp.root') outputs.append(ROOTModule.TFile.Open(filename, 'RECREATE', '', compress))
Open a ROOT file with option 'RECREATE' to create a new file (the file will be overwritten if it already exists), and using the ZLIB compression algorithm (with compression level 1) for better compatibility with older ROOT versions (see https://root.cern.ch/doc/v614/release-notes.html#important-notice ). :param data_out: :param outputs: :return:
entailment
def write(self, data_in, data_out, *args, **kwargs): """ :param data_in: :type data_in: hepconverter.parsers.ParsedData :param data_out: filelike object :type data_out: file :param args: :param kwargs: """ self._get_tables(data_in) self.file_emulation = False outputs = [] self._prepare_outputs(data_out, outputs) output = outputs[0] for i in xrange(len(self.tables)): table = self.tables[i] self._write_table(output, table) if data_out != output and hasattr(data_out, 'write'): output.Flush() output.ReOpen('read') file_size = output.GetSize() buff = bytearray(file_size) output.ReadBuffer(buff, file_size) data_out.write(buff) if self.file_emulation: filename = output.GetName() output.Close()
:param data_in: :type data_in: hepconverter.parsers.ParsedData :param data_out: filelike object :type data_out: file :param args: :param kwargs:
entailment
def _pairwise(iterable): """ itertools recipe "s -> (s0,s1), (s1,s2), (s2, s3), ... """ a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
itertools recipe "s -> (s0,s1), (s1,s2), (s2, s3), ...
entailment
def _groups_of(length, total_length): """ Return an iterator of tuples for slicing, in 'length' chunks. Parameters ---------- length : int Length of each chunk. total_length : int Length of the object we are slicing Returns ------- iterable of tuples Values defining a slice range resulting in length 'length'. """ indices = tuple(range(0, total_length, length)) + (None, ) return _pairwise(indices)
Return an iterator of tuples for slicing, in 'length' chunks. Parameters ---------- length : int Length of each chunk. total_length : int Length of the object we are slicing Returns ------- iterable of tuples Values defining a slice range resulting in length 'length'.
entailment
def save(sources, targets, masked=False): """ Save the numeric results of each source into its corresponding target. Parameters ---------- sources: list The list of source arrays for saving from; limited to length 1. targets: list The list of target arrays for saving to; limited to length 1. masked: boolean Uses a masked array from sources if True. """ # TODO: Remove restriction assert len(sources) == 1 and len(targets) == 1 array = sources[0] target = targets[0] # Request bitesize pieces of the source and assign them to the # target. # NB. This algorithm does not use the minimal number of chunks. # e.g. If the second dimension could be sliced as 0:99, 99:100 # then clearly the first dimension would have to be single # slices for the 0:99 case, but could be bigger slices for the # 99:100 case. # It's not yet clear if this really matters. all_slices = _all_slices(array) for index in np.ndindex(*[len(slices) for slices in all_slices]): keys = tuple(slices[i] for slices, i in zip(all_slices, index)) if masked: target[keys] = array[keys].masked_array() else: target[keys] = array[keys].ndarray()
Save the numeric results of each source into its corresponding target. Parameters ---------- sources: list The list of source arrays for saving from; limited to length 1. targets: list The list of target arrays for saving to; limited to length 1. masked: boolean Uses a masked array from sources if True.
entailment
def count(a, axis=None): """ Count the non-masked elements of the array along the given axis. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :return: The Array representing the requested mean. :rtype: Array """ axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) return _Aggregation(a, axes[0], _CountStreamsHandler, _CountMaskedStreamsHandler, np.dtype('i'), {})
Count the non-masked elements of the array along the given axis. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :return: The Array representing the requested mean. :rtype: Array
entailment
def min(a, axis=None): """ Request the minimum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose minimum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested mean. """ axes = _normalise_axis(axis, a) assert axes is not None and len(axes) == 1 return _Aggregation(a, axes[0], _MinStreamsHandler, _MinMaskedStreamsHandler, a.dtype, {})
Request the minimum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose minimum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested mean.
entailment
def max(a, axis=None): """ Request the maximum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose maximum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested max. """ axes = _normalise_axis(axis, a) assert axes is not None and len(axes) == 1 return _Aggregation(a, axes[0], _MaxStreamsHandler, _MaxMaskedStreamsHandler, a.dtype, {})
Request the maximum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose maximum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested max.
entailment
def sum(a, axis=None): """ Request the sum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose summation is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested sum. """ axes = _normalise_axis(axis, a) assert axes is not None and len(axes) == 1 return _Aggregation(a, axes[0], _SumStreamsHandler, _SumMaskedStreamsHandler, a.dtype, {})
Request the sum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose summation is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested sum.
entailment
def mean(a, axis=None, mdtol=1): """ Request the mean of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param float mdtol: Tolerance of missing data. The value in each element of the resulting array will be masked if the fraction of masked data contributing to that element exceeds mdtol. mdtol=0 means no missing data is tolerated while mdtol=1 will mean the resulting element will be masked if and only if all the contributing elements of the source array are masked. Defaults to 1. :return: The Array representing the requested mean. :rtype: Array """ axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype kwargs = dict(mdtol=mdtol) return _Aggregation(a, axes[0], _MeanStreamsHandler, _MeanMaskedStreamsHandler, dtype, kwargs)
Request the mean of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param float mdtol: Tolerance of missing data. The value in each element of the resulting array will be masked if the fraction of masked data contributing to that element exceeds mdtol. mdtol=0 means no missing data is tolerated while mdtol=1 will mean the resulting element will be masked if and only if all the contributing elements of the source array are masked. Defaults to 1. :return: The Array representing the requested mean. :rtype: Array
entailment
def std(a, axis=None, ddof=0): """ Request the standard deviation of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param int ddof: Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. :return: The Array representing the requested standard deviation. :rtype: Array """ axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype return _Aggregation(a, axes[0], _StdStreamsHandler, _StdMaskedStreamsHandler, dtype, dict(ddof=ddof))
Request the standard deviation of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param int ddof: Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. :return: The Array representing the requested standard deviation. :rtype: Array
entailment
def var(a, axis=None, ddof=0): """ Request the variance of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param int ddof: Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. :return: The Array representing the requested variance. :rtype: Array """ axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype return _Aggregation(a, axes[0], _VarStreamsHandler, _VarMaskedStreamsHandler, dtype, dict(ddof=ddof))
Request the variance of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param int ddof: Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. :return: The Array representing the requested variance. :rtype: Array
entailment
def _ufunc_wrapper(ufunc, name=None): """ A function to generate the top level biggus ufunc wrappers. """ if not isinstance(ufunc, np.ufunc): raise TypeError('{} is not a ufunc'.format(ufunc)) ufunc_name = ufunc.__name__ # Get hold of the masked array equivalent, if it exists. ma_ufunc = getattr(np.ma, ufunc_name, None) if ufunc.nin == 2 and ufunc.nout == 1: func = _dual_input_fn_wrapper('np.{}'.format(ufunc_name), ufunc, ma_ufunc, name) elif ufunc.nin == 1 and ufunc.nout == 1: func = _unary_fn_wrapper('np.{}'.format(ufunc_name), ufunc, ma_ufunc, name) else: raise ValueError('Unsupported ufunc {!r} with {} input arrays & {} ' 'output arrays.'.format(ufunc_name, ufunc.nin, ufunc.nout)) return func
A function to generate the top level biggus ufunc wrappers.
entailment
def _sliced_shape(shape, keys): """ Returns the shape that results from slicing an array of the given shape by the given keys. >>> _sliced_shape(shape=(52350, 70, 90, 180), ... keys=(np.newaxis, slice(None, 10), 3, ... slice(None), slice(2, 3))) (1, 10, 90, 1) """ keys = _full_keys(keys, len(shape)) sliced_shape = [] shape_dim = -1 for key in keys: shape_dim += 1 if _is_scalar(key): continue elif isinstance(key, slice): size = len(range(*key.indices(shape[shape_dim]))) sliced_shape.append(size) elif isinstance(key, np.ndarray) and key.dtype == np.dtype('bool'): # Numpy boolean indexing. sliced_shape.append(builtins.sum(key)) elif isinstance(key, (tuple, np.ndarray)): sliced_shape.append(len(key)) elif key is np.newaxis: shape_dim -= 1 sliced_shape.append(1) else: raise ValueError('Invalid indexing object "{}"'.format(key)) sliced_shape = tuple(sliced_shape) return sliced_shape
Returns the shape that results from slicing an array of the given shape by the given keys. >>> _sliced_shape(shape=(52350, 70, 90, 180), ... keys=(np.newaxis, slice(None, 10), 3, ... slice(None), slice(2, 3))) (1, 10, 90, 1)
entailment
def _full_keys(keys, ndim): """ Given keys such as those passed to ``__getitem__`` for an array of ndim, return a fully expanded tuple of keys. In all instances, the result of this operation should follow: array[keys] == array[_full_keys(keys, array.ndim)] """ if not isinstance(keys, tuple): keys = (keys,) # Make keys mutable, and take a copy. keys = list(keys) # Count the number of keys which actually slice a dimension. n_keys_non_newaxis = len([key for key in keys if key is not np.newaxis]) # Numpy allows an extra dimension to be an Ellipsis, we remove it here # if Ellipsis is in keys, if this doesn't trigger we will raise an # IndexError. is_ellipsis = [key is Ellipsis for key in keys] if n_keys_non_newaxis - 1 >= ndim and any(is_ellipsis): # Remove the left-most Ellipsis, as numpy does. keys.pop(is_ellipsis.index(True)) n_keys_non_newaxis -= 1 if n_keys_non_newaxis > ndim: raise IndexError('Dimensions are over specified for indexing.') lh_keys = [] # Keys, with the last key first. rh_keys = [] take_from_left = True while keys: if take_from_left: next_key = keys.pop(0) keys_list = lh_keys else: next_key = keys.pop(-1) keys_list = rh_keys if next_key is Ellipsis: next_key = slice(None) take_from_left = not take_from_left keys_list.append(next_key) middle = [slice(None)] * (ndim - n_keys_non_newaxis) return tuple(lh_keys + middle + rh_keys[::-1])
Given keys such as those passed to ``__getitem__`` for an array of ndim, return a fully expanded tuple of keys. In all instances, the result of this operation should follow: array[keys] == array[_full_keys(keys, array.ndim)]
entailment
def ensure_array(array): """ Assert that the given array is an Array subclass (or numpy array). If the given array is a numpy.ndarray an appropriate NumpyArrayAdapter instance is created, otherwise the passed array must be a subclass of :class:`Array` else a TypeError will be raised. """ if not isinstance(array, Array): if isinstance(array, np.ndarray): array = NumpyArrayAdapter(array) elif np.isscalar(array): array = ConstantArray([], array) else: raise TypeError('The given array should be a `biggus.Array` ' 'instance, got {}.'.format(type(array))) return array
Assert that the given array is an Array subclass (or numpy array). If the given array is a numpy.ndarray an appropriate NumpyArrayAdapter instance is created, otherwise the passed array must be a subclass of :class:`Array` else a TypeError will be raised.
entailment
def size(array): """ Return a human-readable description of the number of bytes required to store the data of the given array. For example:: >>> array.nbytes 14000000 >> biggus.size(array) '13.35 MiB' Parameters ---------- array : array-like object The array object must provide an `nbytes` property. Returns ------- out : str The Array representing the requested mean. """ nbytes = array.nbytes if nbytes < (1 << 10): size = '{} B'.format(nbytes) elif nbytes < (1 << 20): size = '{:.02f} KiB'.format(nbytes / (1 << 10)) elif nbytes < (1 << 30): size = '{:.02f} MiB'.format(nbytes / (1 << 20)) elif nbytes < (1 << 40): size = '{:.02f} GiB'.format(nbytes / (1 << 30)) else: size = '{:.02f} TiB'.format(nbytes / (1 << 40)) return size
Return a human-readable description of the number of bytes required to store the data of the given array. For example:: >>> array.nbytes 14000000 >> biggus.size(array) '13.35 MiB' Parameters ---------- array : array-like object The array object must provide an `nbytes` property. Returns ------- out : str The Array representing the requested mean.
entailment
def output(self, chunk): """ Dispatch the given Chunk onto all the registered output queues. If the chunk is None, it is silently ignored. """ if chunk is not None: for queue in self.output_queues: queue.put(chunk)
Dispatch the given Chunk onto all the registered output queues. If the chunk is None, it is silently ignored.
entailment
def run(self): """ Emit the Chunk instances which cover the underlying Array. The Array is divided into chunks with a size limit of MAX_CHUNK_SIZE which are emitted into all registered output queues. """ try: chunk_index = self.chunk_index_gen(self.array.shape, self.iteration_order) for key in chunk_index: # Now we have the slices that describe the next chunk. # For example, key might be equivalent to # `[11:12, 0:3, :, :]`. # Simply "realise" the data for that region and emit it # as a Chunk to all registered output queues. if self.masked: data = self.array[key].masked_array() else: data = self.array[key].ndarray() output_chunk = Chunk(key, data) self.output(output_chunk) except: self.abort() raise else: for queue in self.output_queues: queue.put(QUEUE_FINISHED)
Emit the Chunk instances which cover the underlying Array. The Array is divided into chunks with a size limit of MAX_CHUNK_SIZE which are emitted into all registered output queues.
entailment
def add_input_nodes(self, input_nodes): """ Set the given nodes as inputs for this node. Creates a limited-size queue.Queue for each input node and registers each queue as an output of its corresponding node. """ self.input_queues = [queue.Queue(maxsize=3) for _ in input_nodes] for input_node, input_queue in zip(input_nodes, self.input_queues): input_node.add_output_queue(input_queue)
Set the given nodes as inputs for this node. Creates a limited-size queue.Queue for each input node and registers each queue as an output of its corresponding node.
entailment
def run(self): """ Process the input queues in lock-step, and push any results to the registered output queues. """ try: while True: input_chunks = [input.get() for input in self.input_queues] for input in self.input_queues: input.task_done() if any(chunk is QUEUE_ABORT for chunk in input_chunks): self.abort() return if any(chunk is QUEUE_FINISHED for chunk in input_chunks): break self.output(self.process_chunks(input_chunks)) # Finalise the final chunk (process_chunks does this for all # but the last chunk). self.output(self.finalise()) except: self.abort() raise else: for queue in self.output_queues: queue.put(QUEUE_FINISHED)
Process the input queues in lock-step, and push any results to the registered output queues.
entailment
def process_chunks(self, chunks): """ Store the incoming chunk at the corresponding position in the result array. """ chunk, = chunks if chunk.keys: self.result[chunk.keys] = chunk.data else: self.result[...] = chunk.data
Store the incoming chunk at the corresponding position in the result array.
entailment
def _cleanup_new_key(self, key, size, axis): """ Return a key of type int, slice, or tuple that is guaranteed to be valid for the given dimension size. Raises IndexError/TypeError for invalid keys. """ if _is_scalar(key): if key >= size or key < -size: msg = 'index {0} is out of bounds for axis {1} with' \ ' size {2}'.format(key, axis, size) raise IndexError(msg) elif isinstance(key, slice): pass elif isinstance(key, np.ndarray) and key.dtype == np.dtype('bool'): if key.size > size: msg = 'too many boolean indices. Boolean index array ' \ 'of size {0} is greater than axis {1} with ' \ 'size {2}'.format(key.size, axis, size) raise IndexError(msg) elif isinstance(key, collections.Iterable) and \ not isinstance(key, six.string_types): # Make sure we capture the values in case we've # been given a one-shot iterable, like a generator. key = tuple(key) for sub_key in key: if sub_key >= size or sub_key < -size: msg = 'index {0} is out of bounds for axis {1}' \ ' with size {2}'.format(sub_key, axis, size) raise IndexError(msg) else: raise TypeError('invalid key {!r}'.format(key)) return key
Return a key of type int, slice, or tuple that is guaranteed to be valid for the given dimension size. Raises IndexError/TypeError for invalid keys.
entailment
def _remap_new_key(self, indices, new_key, axis): """ Return a key of type int, slice, or tuple that represents the combination of new_key with the given indices. Raises IndexError/TypeError for invalid keys. """ size = len(indices) if _is_scalar(new_key): if new_key >= size or new_key < -size: msg = 'index {0} is out of bounds for axis {1}' \ ' with size {2}'.format(new_key, axis, size) raise IndexError(msg) result_key = indices[new_key] elif isinstance(new_key, slice): result_key = indices.__getitem__(new_key) elif isinstance(new_key, np.ndarray) and \ new_key.dtype == np.dtype('bool'): # Numpy boolean indexing. if new_key.size > size: msg = 'too many boolean indices. Boolean index array ' \ 'of size {0} is greater than axis {1} with ' \ 'size {2}'.format(new_key.size, axis, size) raise IndexError(msg) result_key = tuple(np.array(indices)[new_key]) elif isinstance(new_key, collections.Iterable) and \ not isinstance(new_key, six.string_types): # Make sure we capture the values in case we've # been given a one-shot iterable, like a generator. new_key = tuple(new_key) for sub_key in new_key: if sub_key >= size or sub_key < -size: msg = 'index {0} is out of bounds for axis {1}' \ ' with size {2}'.format(sub_key, axis, size) raise IndexError(msg) result_key = tuple(indices[key] for key in new_key) else: raise TypeError('invalid key {!r}'.format(new_key)) return result_key
Return a key of type int, slice, or tuple that represents the combination of new_key with the given indices. Raises IndexError/TypeError for invalid keys.
entailment
def _apply_axes_mapping(self, target, inverse=False): """ Apply the transposition to the target iterable. Parameters ---------- target - iterable The iterable to transpose. This would be suitable for things such as a shape as well as a list of ``__getitem__`` keys. inverse - bool Whether to map old dimension to new dimension (forward), or new dimension to old dimension (inverse). Default is False (forward). Returns ------- A tuple derived from target which has been ordered based on the new axes. """ if len(target) != self.ndim: raise ValueError('The target iterable is of length {}, but ' 'should be of length {}.'.format(len(target), self.ndim)) if inverse: axis_map = self._inverse_axes_map else: axis_map = self._forward_axes_map result = [None] * self.ndim for axis, item in enumerate(target): result[axis_map[axis]] = item return tuple(result)
Apply the transposition to the target iterable. Parameters ---------- target - iterable The iterable to transpose. This would be suitable for things such as a shape as well as a list of ``__getitem__`` keys. inverse - bool Whether to map old dimension to new dimension (forward), or new dimension to old dimension (inverse). Default is False (forward). Returns ------- A tuple derived from target which has been ordered based on the new axes.
entailment
def output_keys(self, source_keys): """ Given input chunk keys, compute what keys will be needed to put the result into the result array. As an example of where this gets used - when we aggregate on a particular axis, the source keys may be ``(0:2, None:None)``, but for an aggregation on axis 0, they would result in target values on dimension 2 only and so be ``(None: None, )``. """ keys = list(source_keys) # Remove the aggregated axis from the keys. del keys[self.axis] return tuple(keys)
Given input chunk keys, compute what keys will be needed to put the result into the result array. As an example of where this gets used - when we aggregate on a particular axis, the source keys may be ``(0:2, None:None)``, but for an aggregation on axis 0, they would result in target values on dimension 2 only and so be ``(None: None, )``.
entailment
def scalarmult_B(e): """ Implements scalarmult(B, e) more efficiently. """ # scalarmult(B, l) is the identity e = e % l P = ident for i in range(253): if e & 1: P = edwards_add(P, Bpow[i]) e = e // 2 assert e == 0, e return P
Implements scalarmult(B, e) more efficiently.
entailment
def publickey_unsafe(sk): """ Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. """ h = H(sk) a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2)) A = scalarmult_B(a) return encodepoint(A)
Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only.
entailment
def generate_public_and_private(): """ <Purpose> Generate a pair of ed25519 public and private keys with PyNaCl. The public and private keys returned conform to 'securesystemslib.formats.ED25519PULIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respectively, and have the form: '\xa2F\x99\xe0\x86\x80%\xc8\xee\x11\xb95T\xd9\...' An ed25519 seed key is a random 32-byte string. Public keys are also 32 bytes. >>> public, private = generate_public_and_private() >>> securesystemslib.formats.ED25519PUBLIC_SCHEMA.matches(public) True >>> securesystemslib.formats.ED25519SEED_SCHEMA.matches(private) True <Arguments> None. <Exceptions> securesystemslib.exceptions.UnsupportedLibraryError, if the PyNaCl ('nacl') module is unavailable. NotImplementedError, if a randomness source is not found by 'os.urandom'. <Side Effects> The ed25519 keys are generated by first creating a random 32-byte seed with os.urandom() and then calling PyNaCl's nacl.signing.SigningKey(). <Returns> A (public, private) tuple that conform to 'securesystemslib.formats.ED25519PUBLIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respectively. """ # Generate ed25519's seed key by calling os.urandom(). The random bytes # returned should be suitable for cryptographic use and is OS-specific. # Raise 'NotImplementedError' if a randomness source is not found. # ed25519 seed keys are fixed at 32 bytes (256-bit keys). # http://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ seed = os.urandom(32) public = None # Generate the public key. PyNaCl (i.e., 'nacl' module) performs the actual # key generation. try: nacl_key = nacl.signing.SigningKey(seed) public = nacl_key.verify_key.encode(encoder=nacl.encoding.RawEncoder()) except NameError: # pragma: no cover raise securesystemslib.exceptions.UnsupportedLibraryError('The PyNaCl' ' library and/or its dependencies unavailable.') return public, seed
<Purpose> Generate a pair of ed25519 public and private keys with PyNaCl. The public and private keys returned conform to 'securesystemslib.formats.ED25519PULIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respectively, and have the form: '\xa2F\x99\xe0\x86\x80%\xc8\xee\x11\xb95T\xd9\...' An ed25519 seed key is a random 32-byte string. Public keys are also 32 bytes. >>> public, private = generate_public_and_private() >>> securesystemslib.formats.ED25519PUBLIC_SCHEMA.matches(public) True >>> securesystemslib.formats.ED25519SEED_SCHEMA.matches(private) True <Arguments> None. <Exceptions> securesystemslib.exceptions.UnsupportedLibraryError, if the PyNaCl ('nacl') module is unavailable. NotImplementedError, if a randomness source is not found by 'os.urandom'. <Side Effects> The ed25519 keys are generated by first creating a random 32-byte seed with os.urandom() and then calling PyNaCl's nacl.signing.SigningKey(). <Returns> A (public, private) tuple that conform to 'securesystemslib.formats.ED25519PUBLIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respectively.
entailment
def create_signature(public_key, private_key, data, scheme): """ <Purpose> Return a (signature, scheme) tuple, where the signature scheme is 'ed25519' and is always generated by PyNaCl (i.e., 'nacl'). The signature returned conforms to 'securesystemslib.formats.ED25519SIGNATURE_SCHEMA', and has the form: '\xae\xd7\x9f\xaf\x95{bP\x9e\xa8YO Z\x86\x9d...' A signature is a 64-byte string. >>> public, private = generate_public_and_private() >>> data = b'The quick brown fox jumps over the lazy dog' >>> scheme = 'ed25519' >>> signature, scheme = \ create_signature(public, private, data, scheme) >>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature) True >>> scheme == 'ed25519' True >>> signature, scheme = \ create_signature(public, private, data, scheme) >>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature) True >>> scheme == 'ed25519' True <Arguments> public: The ed25519 public key, which is a 32-byte string. private: The ed25519 private key, which is a 32-byte string. data: Data object used by create_signature() to generate the signature. scheme: The signature scheme used to generate the signature. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if a signature cannot be created. <Side Effects> nacl.signing.SigningKey.sign() called to generate the actual signature. <Returns> A signature dictionary conformat to 'securesystemslib.format.SIGNATURE_SCHEMA'. ed25519 signatures are 64 bytes, however, the hexlified signature is stored in the dictionary returned. """ # Does 'public_key' have the correct format? # This check will ensure 'public_key' conforms to # 'securesystemslib.formats.ED25519PUBLIC_SCHEMA', which must have length 32 # bytes. Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ED25519PUBLIC_SCHEMA.check_match(public_key) # Is 'private_key' properly formatted? securesystemslib.formats.ED25519SEED_SCHEMA.check_match(private_key) # Is 'scheme' properly formatted? securesystemslib.formats.ED25519_SIG_SCHEMA.check_match(scheme) # Signing the 'data' object requires a seed and public key. # nacl.signing.SigningKey.sign() generates the signature. public = public_key private = private_key signature = None # An if-clause is not strictly needed here, since 'ed25519' is the only # currently supported scheme. Nevertheless, include the conditional # statement to accommodate schemes that might be added in the future. if scheme == 'ed25519': try: nacl_key = nacl.signing.SigningKey(private) nacl_sig = nacl_key.sign(data) signature = nacl_sig.signature # The unit tests expect required libraries to be installed. except NameError: # pragma: no cover raise securesystemslib.exceptions.UnsupportedLibraryError('The PyNaCl' ' library and/or its dependencies unavailable.') except (ValueError, TypeError, nacl.exceptions.CryptoError) as e: raise securesystemslib.exceptions.CryptoError('An "ed25519" signature' ' could not be created with PyNaCl.' + str(e)) # This is a defensive check for a valid 'scheme', which should have already # been validated in the check_match() above. else: #pragma: no cover raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported' ' signature scheme is specified: ' + repr(scheme)) return signature, scheme
<Purpose> Return a (signature, scheme) tuple, where the signature scheme is 'ed25519' and is always generated by PyNaCl (i.e., 'nacl'). The signature returned conforms to 'securesystemslib.formats.ED25519SIGNATURE_SCHEMA', and has the form: '\xae\xd7\x9f\xaf\x95{bP\x9e\xa8YO Z\x86\x9d...' A signature is a 64-byte string. >>> public, private = generate_public_and_private() >>> data = b'The quick brown fox jumps over the lazy dog' >>> scheme = 'ed25519' >>> signature, scheme = \ create_signature(public, private, data, scheme) >>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature) True >>> scheme == 'ed25519' True >>> signature, scheme = \ create_signature(public, private, data, scheme) >>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature) True >>> scheme == 'ed25519' True <Arguments> public: The ed25519 public key, which is a 32-byte string. private: The ed25519 private key, which is a 32-byte string. data: Data object used by create_signature() to generate the signature. scheme: The signature scheme used to generate the signature. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if a signature cannot be created. <Side Effects> nacl.signing.SigningKey.sign() called to generate the actual signature. <Returns> A signature dictionary conformat to 'securesystemslib.format.SIGNATURE_SCHEMA'. ed25519 signatures are 64 bytes, however, the hexlified signature is stored in the dictionary returned.
entailment
def verify_signature(public_key, scheme, signature, data, use_pynacl=False): """ <Purpose> Determine whether the private key corresponding to 'public_key' produced 'signature'. verify_signature() will use the public key, the 'scheme' and 'sig', and 'data' arguments to complete the verification. >>> public, private = generate_public_and_private() >>> data = b'The quick brown fox jumps over the lazy dog' >>> scheme = 'ed25519' >>> signature, scheme = \ create_signature(public, private, data, scheme) >>> verify_signature(public, scheme, signature, data, use_pynacl=False) True >>> verify_signature(public, scheme, signature, data, use_pynacl=True) True >>> bad_data = b'The sly brown fox jumps over the lazy dog' >>> bad_signature, scheme = \ create_signature(public, private, bad_data, scheme) >>> verify_signature(public, scheme, bad_signature, data, use_pynacl=False) False <Arguments> public_key: The public key is a 32-byte string. scheme: 'ed25519' signature scheme used by either the pure python implementation (i.e., ed25519.py) or PyNacl (i.e., 'nacl'). signature: The signature is a 64-byte string. data: Data object used by securesystemslib.ed25519_keys.create_signature() to generate 'signature'. 'data' is needed here to verify the signature. use_pynacl: True, if the ed25519 signature should be verified by PyNaCl. False, if the signature should be verified with the pure Python implementation of ed25519 (slower). <Exceptions> securesystemslib.exceptions.UnsupportedAlgorithmError. Raised if the signature scheme 'scheme' is not one supported by securesystemslib.ed25519_keys.create_signature(). securesystemslib.exceptions.FormatError. Raised if the arguments are improperly formatted. <Side Effects> securesystemslib._vendor.ed25519.ed25519.checkvalid() called to do the actual verification. nacl.signing.VerifyKey.verify() called if 'use_pynacl' is True. <Returns> Boolean. True if the signature is valid, False otherwise. """ # Does 'public_key' have the correct format? # This check will ensure 'public_key' conforms to # 'securesystemslib.formats.ED25519PUBLIC_SCHEMA', which must have length 32 # bytes. Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ED25519PUBLIC_SCHEMA.check_match(public_key) # Is 'scheme' properly formatted? securesystemslib.formats.ED25519_SIG_SCHEMA.check_match(scheme) # Is 'signature' properly formatted? securesystemslib.formats.ED25519SIGNATURE_SCHEMA.check_match(signature) # Is 'use_pynacl' properly formatted? securesystemslib.formats.BOOLEAN_SCHEMA.check_match(use_pynacl) # Verify 'signature'. Before returning the Boolean result, ensure 'ed25519' # was used as the signature scheme. Raise # 'securesystemslib.exceptions.UnsupportedLibraryError' if 'use_pynacl' is # True but 'nacl' is unavailable. public = public_key valid_signature = False if scheme in _SUPPORTED_ED25519_SIGNING_SCHEMES: if use_pynacl: try: nacl_verify_key = nacl.signing.VerifyKey(public) nacl_message = nacl_verify_key.verify(data, signature) valid_signature = True # The unit tests expect PyNaCl to be installed. except NameError: # pragma: no cover raise securesystemslib.exceptions.UnsupportedLibraryError('The PyNaCl' ' library and/or its dependencies unavailable.') except nacl.exceptions.BadSignatureError: pass # Verify 'ed25519' signature with the pure Python implementation. else: try: securesystemslib._vendor.ed25519.ed25519.checkvalid(signature, data, public) valid_signature = True # The pure Python implementation raises 'Exception' if 'signature' is # invalid. except Exception as e: pass # This is a defensive check for a valid 'scheme', which should have already # been validated in the ED25519_SIG_SCHEMA.check_match(scheme) above. else: #pragma: no cover message = 'Unsupported ed25519 signature scheme: ' + repr(scheme) + '.\n' + \ 'Supported schemes: ' + repr(_SUPPORTED_ED25519_SIGNING_SCHEMES) + '.' raise securesystemslib.exceptions.UnsupportedAlgorithmError(message) return valid_signature
<Purpose> Determine whether the private key corresponding to 'public_key' produced 'signature'. verify_signature() will use the public key, the 'scheme' and 'sig', and 'data' arguments to complete the verification. >>> public, private = generate_public_and_private() >>> data = b'The quick brown fox jumps over the lazy dog' >>> scheme = 'ed25519' >>> signature, scheme = \ create_signature(public, private, data, scheme) >>> verify_signature(public, scheme, signature, data, use_pynacl=False) True >>> verify_signature(public, scheme, signature, data, use_pynacl=True) True >>> bad_data = b'The sly brown fox jumps over the lazy dog' >>> bad_signature, scheme = \ create_signature(public, private, bad_data, scheme) >>> verify_signature(public, scheme, bad_signature, data, use_pynacl=False) False <Arguments> public_key: The public key is a 32-byte string. scheme: 'ed25519' signature scheme used by either the pure python implementation (i.e., ed25519.py) or PyNacl (i.e., 'nacl'). signature: The signature is a 64-byte string. data: Data object used by securesystemslib.ed25519_keys.create_signature() to generate 'signature'. 'data' is needed here to verify the signature. use_pynacl: True, if the ed25519 signature should be verified by PyNaCl. False, if the signature should be verified with the pure Python implementation of ed25519 (slower). <Exceptions> securesystemslib.exceptions.UnsupportedAlgorithmError. Raised if the signature scheme 'scheme' is not one supported by securesystemslib.ed25519_keys.create_signature(). securesystemslib.exceptions.FormatError. Raised if the arguments are improperly formatted. <Side Effects> securesystemslib._vendor.ed25519.ed25519.checkvalid() called to do the actual verification. nacl.signing.VerifyKey.verify() called if 'use_pynacl' is True. <Returns> Boolean. True if the signature is valid, False otherwise.
entailment
def _delete_file(fileName, n=10): """Cleanly deletes a file in `n` attempts (if necessary)""" status = False count = 0 while not status and count < n: try: _os.remove(fileName) except OSError: count += 1 _time.sleep(0.2) else: status = True return status
Cleanly deletes a file in `n` attempts (if necessary)
entailment
def zDDEInit(self): """Initiates link with OpticStudio DDE server""" self.pyver = _get_python_version() # do this only one time or when there is no channel if _PyZDDE.liveCh==0: try: _PyZDDE.server = _dde.CreateServer() _PyZDDE.server.Create("ZCLIENT") except Exception as err: _sys.stderr.write("{}: DDE server may be in use!".format(str(err))) return -1 # Try to create individual conversations for each ZEMAX application. self.conversation = _dde.CreateConversation(_PyZDDE.server) try: self.conversation.ConnectTo(self.appName, " ") except Exception as err: _sys.stderr.write("{}.\nOpticStudio UI may not be running!\n".format(str(err))) # should close the DDE server if it exist self.zDDEClose() return -1 else: _PyZDDE.liveCh += 1 self.connection = True return 0
Initiates link with OpticStudio DDE server
entailment
def zDDEClose(self): """Close the DDE link with Zemax server""" if _PyZDDE.server and not _PyZDDE.liveCh: _PyZDDE.server.Shutdown(self.conversation) _PyZDDE.server = 0 elif _PyZDDE.server and self.connection and _PyZDDE.liveCh == 1: _PyZDDE.server.Shutdown(self.conversation) self.connection = False self.appName = '' _PyZDDE.liveCh -= 1 _PyZDDE.server = 0 elif self.connection: _PyZDDE.server.Shutdown(self.conversation) self.connection = False self.appName = '' _PyZDDE.liveCh -= 1 return 0
Close the DDE link with Zemax server
entailment
def setTimeout(self, time): """Set global timeout value, in seconds, for all DDE calls""" self.conversation.SetDDETimeout(round(time)) return self.conversation.GetDDETimeout()
Set global timeout value, in seconds, for all DDE calls
entailment
def _sendDDEcommand(self, cmd, timeout=None): """Send command to DDE client""" reply = self.conversation.Request(cmd, timeout) if self.pyver > 2: reply = reply.decode('ascii').rstrip() return reply
Send command to DDE client
entailment
def zGetUpdate(self): """Update the lens""" status,ret = -998, None ret = self._sendDDEcommand("GetUpdate") if ret != None: status = int(ret) #Note: Zemax returns -1 if GetUpdate fails. return status
Update the lens
entailment
def zLoadFile(self, fileName, append=None): """Loads a zmx file into the DDE server""" reply = None if append: cmd = "LoadFile,{},{}".format(fileName, append) else: cmd = "LoadFile,{}".format(fileName) reply = self._sendDDEcommand(cmd) if reply: return int(reply) #Note: Zemax returns -999 if update fails. else: return -998
Loads a zmx file into the DDE server
entailment
def zPushLens(self, update=None, timeout=None): """Copy lens in the Zemax DDE server into LDE""" reply = None if update == 1: reply = self._sendDDEcommand('PushLens,1', timeout) elif update == 0 or update is None: reply = self._sendDDEcommand('PushLens,0', timeout) else: raise ValueError('Invalid value for flag') if reply: return int(reply) # Note: Zemax returns -999 if push lens fails else: return -998
Copy lens in the Zemax DDE server into LDE
entailment
def zSaveFile(self, fileName): """Saves the lens currently loaded in the server to a Zemax file """ cmd = "SaveFile,{}".format(fileName) reply = self._sendDDEcommand(cmd) return int(float(reply.rstrip()))
Saves the lens currently loaded in the server to a Zemax file
entailment
def zSyncWithUI(self): """Turn on sync-with-ui""" if not OpticalSystem._dde_link: OpticalSystem._dde_link = _get_new_dde_link() if not self._sync_ui_file: self._sync_ui_file = _get_sync_ui_filename() self._sync_ui = True
Turn on sync-with-ui
entailment
def zPushLens(self, update=None): """Push lens in ZOS COM server to UI""" self.SaveAs(self._sync_ui_file) OpticalSystem._dde_link.zLoadFile(self._sync_ui_file) OpticalSystem._dde_link.zPushLens(update)
Push lens in ZOS COM server to UI
entailment
def zGetRefresh(self): """Copy lens in UI to headless ZOS COM server""" OpticalSystem._dde_link.zGetRefresh() OpticalSystem._dde_link.zSaveFile(self._sync_ui_file) self._iopticalsystem.LoadFile (self._sync_ui_file, False)
Copy lens in UI to headless ZOS COM server
entailment
def SaveAs(self, filename): """Saves the current system to the specified file. @param filename: absolute path (string) @return: None @raise: ValueError if path (excluding the zemax file name) is not valid All future calls to `Save()` will use the same file. """ directory, zfile = _os.path.split(filename) if zfile.startswith('pyzos_ui_sync_file'): self._iopticalsystem.SaveAs(filename) else: # regular file if not _os.path.exists(directory): raise ValueError('{} is not valid.'.format(directory)) else: self._file_to_save_on_Save = filename # store to use in Save() self._iopticalsystem.SaveAs(filename)
Saves the current system to the specified file. @param filename: absolute path (string) @return: None @raise: ValueError if path (excluding the zemax file name) is not valid All future calls to `Save()` will use the same file.
entailment
def Save(self): """Saves the current system""" # This method is intercepted to allow ui_sync if self._file_to_save_on_Save: self._iopticalsystem.SaveAs(self._file_to_save_on_Save) else: self._iopticalsystem.Save()
Saves the current system
entailment
def zGetSurfaceData(self, surfNum): """Return surface data""" if self.pMode == 0: # Sequential mode surf_data = _co.namedtuple('surface_data', ['radius', 'thick', 'material', 'semidia', 'conic', 'comment']) surf = self.pLDE.GetSurfaceAt(surfNum) return surf_data(surf.pRadius, surf.pThickness, surf.pMaterial, surf.pSemiDiameter, surf.pConic, surf.pComment) else: raise NotImplementedError('Function not implemented for non-sequential mode')
Return surface data
entailment
def zSetSurfaceData(self, surfNum, radius=None, thick=None, material=None, semidia=None, conic=None, comment=None): """Sets surface data""" if self.pMode == 0: # Sequential mode surf = self.pLDE.GetSurfaceAt(surfNum) if radius is not None: surf.pRadius = radius if thick is not None: surf.pThickness = thick if material is not None: surf.pMaterial = material if semidia is not None: surf.pSemiDiameter = semidia if conic is not None: surf.pConic = conic if comment is not None: surf.pComment = comment else: raise NotImplementedError('Function not implemented for non-sequential mode')
Sets surface data
entailment
def zSetDefaultMeritFunctionSEQ(self, ofType=0, ofData=0, ofRef=0, pupilInteg=0, rings=0, arms=0, obscuration=0, grid=0, delVignetted=False, useGlass=False, glassMin=0, glassMax=1000, glassEdge=0, useAir=False, airMin=0, airMax=1000, airEdge=0, axialSymm=True, ignoreLatCol=False, addFavOper=False, startAt=1, relativeXWgt=1.0, overallWgt=1.0, configNum=0): """Sets the default merit function for Sequential Merit Function Editor Parameters ---------- ofType : integer optimization function type (0=RMS, ...) ofData : integer optimization function data (0=Wavefront, 1=Spot Radius, ...) ofRef : integer optimization function reference (0=Centroid, ...) pupilInteg : integer pupil integration method (0=Gaussian Quadrature, 1=Rectangular Array) rings : integer rings (0=1, 1=2, 2=3, 3=4, ...) arms : integer arms (0=6, 1=8, 2=10, 3=12) obscuration : real obscuration delVignetted : boolean delete vignetted ? useGlass : boolean whether to use Glass settings for thickness boundary glassMin : real glass mininum thickness glassMax : real glass maximum thickness glassEdge : real glass edge thickness useAir : boolean whether to use Air settings for thickness boundary airMin : real air minimum thickness airMax : real air maximum thickness airEdge : real air edge thickness axialSymm : boolean assume axial symmetry ignoreLatCol : boolean ignore latent color addFavOper : boolean add favorite color configNum : integer configuration number (0=All) startAt : integer start at relativeXWgt : real relative X weight overallWgt : real overall weight """ mfe = self.pMFE wizard = mfe.pSEQOptimizationWizard wizard.pType = ofType wizard.pData = ofData wizard.pReference = ofRef wizard.pPupilIntegrationMethod = pupilInteg wizard.pRing = rings wizard.pArm = arms wizard.pObscuration = obscuration wizard.pGrid = grid wizard.pIsDeleteVignetteUsed = delVignetted wizard.pIsGlassUsed = useGlass wizard.pGlassMin = glassMin wizard.pGlassMax = glassMax wizard.pGlassEdge = glassEdge wizard.pIsAirUsed = useAir wizard.pAirMin = airMin wizard.pAirMax = airMax wizard.pAirEdge = airEdge wizard.pIsAssumeAxialSymmetryUsed = axialSymm wizard.pIsIgnoreLateralColorUsed = ignoreLatCol wizard.pConfiguration = configNum wizard.pIsAddFavoriteOperandsUsed = addFavOper wizard.pStartAt = startAt wizard.pRelativeXWeight = relativeXWgt wizard.pOverallWeight = overallWgt wizard.CommonSettings.OK()
Sets the default merit function for Sequential Merit Function Editor Parameters ---------- ofType : integer optimization function type (0=RMS, ...) ofData : integer optimization function data (0=Wavefront, 1=Spot Radius, ...) ofRef : integer optimization function reference (0=Centroid, ...) pupilInteg : integer pupil integration method (0=Gaussian Quadrature, 1=Rectangular Array) rings : integer rings (0=1, 1=2, 2=3, 3=4, ...) arms : integer arms (0=6, 1=8, 2=10, 3=12) obscuration : real obscuration delVignetted : boolean delete vignetted ? useGlass : boolean whether to use Glass settings for thickness boundary glassMin : real glass mininum thickness glassMax : real glass maximum thickness glassEdge : real glass edge thickness useAir : boolean whether to use Air settings for thickness boundary airMin : real air minimum thickness airMax : real air maximum thickness airEdge : real air edge thickness axialSymm : boolean assume axial symmetry ignoreLatCol : boolean ignore latent color addFavOper : boolean add favorite color configNum : integer configuration number (0=All) startAt : integer start at relativeXWgt : real relative X weight overallWgt : real overall weight
entailment
def datetime_to_unix_timestamp(datetime_object): """ <Purpose> Convert 'datetime_object' (in datetime.datetime()) format) to a Unix/POSIX timestamp. For example, Python's time.time() returns a Unix timestamp, and includes the number of microseconds. 'datetime_object' is converted to UTC. >>> datetime_object = datetime.datetime(1985, 10, 26, 1, 22) >>> timestamp = datetime_to_unix_timestamp(datetime_object) >>> timestamp 499137720 <Arguments> datetime_object: The datetime.datetime() object to convert to a Unix timestamp. <Exceptions> securesystemslib.exceptions.FormatError, if 'datetime_object' is not a datetime.datetime() object. <Side Effects> None. <Returns> A unix (posix) timestamp (e.g., 499137660). """ # Is 'datetime_object' a datetime.datetime() object? # Raise 'securesystemslib.exceptions.FormatError' if not. if not isinstance(datetime_object, datetime.datetime): message = repr(datetime_object) + ' is not a datetime.datetime() object.' raise securesystemslib.exceptions.FormatError(message) unix_timestamp = calendar.timegm(datetime_object.timetuple()) return unix_timestamp
<Purpose> Convert 'datetime_object' (in datetime.datetime()) format) to a Unix/POSIX timestamp. For example, Python's time.time() returns a Unix timestamp, and includes the number of microseconds. 'datetime_object' is converted to UTC. >>> datetime_object = datetime.datetime(1985, 10, 26, 1, 22) >>> timestamp = datetime_to_unix_timestamp(datetime_object) >>> timestamp 499137720 <Arguments> datetime_object: The datetime.datetime() object to convert to a Unix timestamp. <Exceptions> securesystemslib.exceptions.FormatError, if 'datetime_object' is not a datetime.datetime() object. <Side Effects> None. <Returns> A unix (posix) timestamp (e.g., 499137660).
entailment