code
stringlengths
1
18.2k
def digests_are_equal(digest1, digest2): """ <Purpose> While protecting against timing attacks, compare the hexadecimal arguments and determine if they are equal. <Arguments> digest1: The first hexadecimal string value to compare. digest2: The second hexadecimal string value to compare. <Exceptions> securesystemslib.ex...
have the appropriate number of objects and object # types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch. securesystemslib.formats.HEX_SCHEMA.check_match(digest1) securesystemslib.formats.HEX_SCHEMA.check_match(digest2) if len(digest1) != len(digest2...
def _default_temporary_directory(self, prefix): """__init__ helper.""" try: self.temporary_file = tempfile.NamedTemporaryFile(prefix=prefix) except OSError as err: # pragma: no cover logger.critical('Cannot create a system temporary directory: '+repr(err)) raise securesystemslib.exceptions.Error(err)
def read(self, size=None): """ <Purpose> Read specified number of bytes. If size is not specified then the whole file is read and the file pointer is placed at the beginning of the file. <Arguments> size: Number of bytes to be read. <Exceptions> securesystemslib.exceptions.FormatError: if 'size' is invalid. <Return> St...
if not (isinstance(size, int) and size > 0): raise securesystemslib.exceptions.FormatError return self.temporary_file.read(size)
def write(self, data, auto_flush=True): """ <Purpose> Writes a data string to the file. <Arguments> data: A string containing some data. auto_flush: Boolean argument, if set to 'True', all data will be flushed from internal buffer. <Exceptions> None. <Return> None. """ self.temporary_file.write(data) if auto_flush: sel...
def move(self, destination_path): """ <Purpose> Copies 'self.temporary_file' to a non-temp file at 'destination_path' and closes 'self.temporary_file' so that it is removed. <Arguments> destination_path: Path to store the file in. <Exceptions> None. <Return> None. """ self.flush() self.seek(0) destination_file = open(d...
flush(). destination_file.flush() os.fsync(destination_file.fileno()) destination_file.close() # 'self.close()' closes temporary file which destroys itself. self.close_temp_file()
def decompress_temp_file_object(self, compression): """ <Purpose> To decompress a compressed temp file object. Decompression is performed on a temp file object that is compressed, this occurs after downloading a compressed file. For instance if a compressed version of some meta file in the repository is downloaded, the...
method, write() can no longer be called. meta.json.gz |...[download] temporary_file (containing meta.json.gz) / \ temporary_file _orig_file containing meta.json containing meta.json.gz (decompressed data) <Arguments> compression: A string indicating the type of compression that was used to compress a file. Only gzip is...
<Side Effects> 'self._orig_file' is used to store the original data of 'temporary_file'. <Return> None. """ # Does 'compression' have the correct format? # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch. securesystemslib.formats.NAME_SCHEMA.check_match(compression) if self._orig_file is not None...
try: gzip_file_object = gzip.GzipFile(fileobj=self.temporary_file, mode='rb') uncompressed_content = gzip_file_object.read() self.temporary_file = tempfile.NamedTemporaryFile() self.temporary_file.write(uncompressed_content) self.flush() except Exception as exception: raise securesystemslib.exceptions.DecompressionErro...
def close_temp_file(self): """ <Purpose> Closes the temporary file object. 'close_temp_file' mimics usual file.close(), however temporary file destroys itself when 'close_temp_file' is called. Further if compression is set, second temporary file instance 'self._orig_file' is also closed so that no open temporary files ...
to explicitly close the original # file object. if self._orig_file is not None: self._orig_file.close()
def matches(self, object): """ <Purpose> Return True if 'object' matches this schema, False if it doesn't. If the caller wishes to signal an error on a failed match, check_match() should be called, which will raise a 'exceptions.FormatError' exception. """ try: self.check_match(object) except securesystemslib.exception...
def get_event(self, *etypes, timeout=None): """ Return a single event object or block until an event is received and return it. - etypes(str): If defined, Slack event type(s) not matching the filter will be ignored. See https://api.slack.com/events for a listing of valid event types. - timeout(int): Max time, in second...
isinstance(e, Exception): raise e self._stats['events_recieved'] += 1 if etypes and e.type not in etypes: if timeout: timeout -= time.time() - start log.debug('ignoring filtered event: {}'.format(e.json)) self._stats['events_dropped'] += 1 return self.get_event(*etypes, timeout=timeout) return e
def events(self, *etypes, idle_timeout=None): """ returns a blocking generator yielding Slack event objects params: - etypes(str): If defined, Slack event type(s) not matching the filter will be ignored. See https://api.slack.com/events for a listing of valid event types. - idle_timeout(int): optional maximum amount of...
timeout reached for events()') return
def send_msg(self, text, channel, confirm=True): """ Send a message to a channel or group via Slack RTM socket, returning the resulting message object params: - text(str): Message text to send - channel(Channel): Target channel - confirm(bool): If True, wait for a reply-to confirmation before returning. """ self._send_...
our message was received for e in self.events(): if e.get('reply_to') == self._send_id: msg.sent = True msg.ts = e.ts return msg else: return msg
def _process_event(self, event): """ Extend event object with User and Channel objects """ if event.get('user'): event.user = self.lookup_user(event.get('user')) if event.get('channel'): event.channel = self.lookup_channel(event.get('channel')) if self.user.id in event.mentions: event.mentions_me = True event.mentions ...
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 ...
: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(...
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()
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 ...
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, qu...
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 ...
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 = securesystem...
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 ...
== '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: ...
repr(SUPPORTED_LIBRARIES))
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> ...
'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 app...
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 cry...
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 fil...
# 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(d...
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 ...
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 unsuppo...
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_objec...
def get_token_stream(source: str) -> CommonTokenStream: """ Get the antlr token stream. """ lexer = LuaLexer(InputStream(source)) stream = CommonTokenStream(lexer) return stream
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)
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)
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)
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)
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-...
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 ...
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...
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()) # Extrac...
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(...
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....
= 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) use...
<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,...
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 an...
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 ad...
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()) signatur...
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 #...
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: #pr...
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
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_an...
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. ...
<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(). securesystemsli...
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.forma...
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_l...
PEM could not be' ' decoded successfully, or contained an unsupported key type: ' + str(e))
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...
>>> 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. secu...
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.ch...
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.') ...
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--...
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 pas...
>>> 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...
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...
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.excep...
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 ...
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 s...
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...
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=seria...
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()
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_SCH...
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 ...
'scheme': 'ed25519', \ 'keyid': \ 'd62247f817883f593cf6c66a5a55292488d457bcf638ae03207dbbba9dbe457d', \ 'keyval': {'public': \ '74addb5ad544a4306b34741bc1175a3613a8d7dc69ff64724243efdec0e301ad', \ 'private': \ '1f26964cc8d4f7ee5f3c5da2fbb7ab35811169573ac367b860a537e47789f8c4'}} >>> passphrase = 'secret' >>> encrypted_k...
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 ...
<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 ch...
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 'pass...
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...
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 cryptogr...
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': \ 'd62247f817883f593cf6c66a5a55292488d457bcf638ae0...
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 dir...
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 dat...
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 correc...
_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
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...
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 accordi...
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'))...
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 gene...
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': '.....
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 su...
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 c...
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) hma...