code
stringlengths
1
18.2k
custom methods monkey patched; and returns an instance of it. """ if hasattr(zos_obj, '_wrapped') or ('CLSID' not in dir(zos_obj)): return zos_obj else: Class = managed_wrapper_class_factory(zos_obj) return Class(zos_obj)
def generate_public_and_private(scheme='ecdsa-sha2-nistp256'): """ <Purpose> Generate a pair of ECDSA public and private keys with one of the supported, external cryptography libraries. The public and private keys returned conform to 'securesystemslib.formats.PEMECDSA_SCHEMA' and 'securesystemslib.formats.PEMECDSA_SCHE...
The private ECDSA private key has the PEM format: '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----' >>> public, private = generate_public_and_private() >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(public) True >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(private) True <Arguments> scheme:...
RFC 5656 (https://tools.ietf.org/html/rfc5656). <Exceptions> securesystemslib.exceptions.FormatError, if 'algorithm' is improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'scheme' is an unsupported algorithm. <Side Effects> None. <Returns> A (public, private) tuple that conform to 'securesy...
'securesystemslib.formats.ECDSA_SCHEME_SCHEMA'. Raise # 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme) public_key = None private_key = None # An if-clause is strictly not needed, since 'ecdsa_sha2-nistp256' is the # only currently supported...
detected any # invalid 'scheme'. This is a defensive check. else: #pragma: no cover raise securesystemslib.exceptions.UnsupportedAlgorithmError('An unsupported' ' scheme specified: ' + repr(scheme) + '.\n Supported' ' algorithms: ' + repr(_SUPPORTED_ECDSA_SCHEMES)) private_pem = private_key.private_bytes(encoding=seria...
def create_signature(public_key, private_key, data, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Return a (signature, scheme) tuple. >>> requested_scheme = 'ecdsa-sha2-nistp256' >>> public, private = generate_public_and_private(requested_scheme) >>> data = b'The quick brown fox jumps over the lazy dog' >>> signature, s...
PEM format. data: Byte data used by create_signature() to generate the signature returned. scheme: The signature scheme used to generate the signature. For example: 'ecdsa-sha2-nistp256'. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoE...
XX bytes, however, the hexlified signature is stored in the dictionary returned. """ # Do 'public_key' and 'private_key' have the correct format? # This check will ensure that the arguments conform to # 'securesystemslib.formats.PEMECDSA_SCHEMA'. Raise # 'securesystemslib.exceptions.FormatError' if the check fails. sec...
this # if-clause isn't strictly needed. Nevertheless, the conditional statement # is included to accommodate multiple schemes that can potentially be added # in the future. if scheme == 'ecdsa-sha2-nistp256': try: private_key = load_pem_private_key(private_key.encode('utf-8'), password=None, backend=default_backend()) ...
above should have already validated it. else: #pragma: no cover raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported' ' signature scheme is specified: ' + repr(scheme)) return signature, scheme
def verify_signature(public_key, scheme, signature, data): """ <Purpose> Verify that 'signature' was produced by the private key associated with 'public_key'. >>> scheme = 'ecdsa-sha2-nistp256' >>> public, private = generate_public_and_private(scheme) >>> data = b'The quick brown fox jumps over the lazy dog' >>> signat...
ECDSA public key in PEM format. The public key is needed to verify 'signature'. scheme: The signature scheme used to generate 'signature'. For example: 'ecdsa-sha2-nistp256'. signature: The signature to be verified, which should have been generated by the private key associated with 'public_key'. 'data'. data: Byte dat...
formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if 'scheme' is not one of the supported signature schemes. <Side Effects> None. <Returns> Boolean, indicating whether the 'signature' of data was generated by the private key associated with 'public_key'. """ # Are the arguments properly formatted? # If ...
else: logger.debug('Loaded a valid ECDSA public key.') # verify() raises an 'InvalidSignature' exception if 'signature' # is invalid. try: ecdsa_key.verify(signature, data, ec.ECDSA(hashes.SHA256())) return True except (TypeError, cryptography.exceptions.InvalidSignature): return False
def create_ecdsa_public_and_private_from_pem(pem, password=None): """ <Purpose> Create public and private ECDSA keys from a private 'pem'. The public and private keys are strings in PEM format: public: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----', private: '-----BEGIN EC PRIVATE KEY----- ... -----END EC PR...
encrypted_pem = create_ecdsa_encrypted_pem(private, passphrase) >>> public, private = create_ecdsa_public_and_private_from_pem(encrypted_pem, passphrase) >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(public) True >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(private) True <Arguments> pem: A string in PEM ...
encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if the ECDSA key pair could not be extracted, possibly due to an unsupported algorithm. <Side Effects> None. <Returns> A dictionary c...
'securesystemslib.formats.ECDSARSA_SCHEMA'. securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem) if password is not None: securesystemslib.formats.PASSWORD_SCHEMA.check_match(password) password = password.encode('utf-8') else: logger.debug('The password/passphrase is unset. The PEM is expected' ' to be unencrypted...
PEM.\n' + str(e)) public = private.public_key() # Serialize public and private keys to PEM format. private = private.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) public = public.public_bytes(encoding=serializ...
def create_ecdsa_encrypted_pem(private_pem, passphrase): """ <Purpose> Return a string in PEM format, where the private part of the ECDSA key is encrypted. The private part of the ECDSA key is encrypted as done by pyca/cryptography: "Encrypt using the best available encryption for a given key's backend. This is a curat...
passphrase = 'secret' >>> encrypted_pem = create_ecdsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_pem: The private ECDSA key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the ECDSA key. '...
key in encrypted PEM format cannot be created. <Side Effects> None. <Returns> A string in PEM format, where the private RSA portion is encrypted. Conforms to 'securesystemslib.formats.PEMECDSA_SCHEMA'. """ # Does 'private_key' have the correct format? # Raise 'securesystemslib.exceptions.FormatError' if the check fails...
encryption_algorithm=serialization.BestAvailableEncryption(passphrase.encode('utf-8'))) return encrypted_private_pem
def reset(self): """Clean any processing data, and prepare object for reuse """ self.current_table = None self.tables = [] self.data = [{}] self.additional_data = {} self.lines = [] self.set_state('document') self.current_file = None self.set_of_energies = set()
def _parse_line(self, file): """Parse single line (or more if particular keyword actually demands it) :param file: :type file: file """ line = self._strip_comments(file.readline()) # check if the file ended if not line: return False # line was empty or it was a comment, continue if line.strip() == '': return True # ret...
reg.group('key').strip() value = reg.group('value') if key in self.mapping[self.current_state]: self.mapping[self.current_state][key](value) elif self.strict: raise BadFormat("unknown key: *%s" % key) else: raise BadFormat("line can not be parsed: %s" % line) return True
def _set_table(self, data): """Set current parsing state to 'table', create new table object and add it to tables collection """ self.set_state('table') self.current_table = HEPTable(index=len(self.tables) + 1) self.tables.append(self.current_table) self.data.append(self.current_table.metadata)
def _parse_table_data(self, data): """Parse dataset data of the original HEPData format :param data: header of the table to be parsed :raise ValueError: """ header = data.split(':') self.current_table.data_header = header for i, h in enumerate(header): header[i] = h.strip() x_count = header.count('x') y_count = header....
to appear before *data: %s" % data) # use deepcopy to avoid references in yaml... may not be required, and will very probably be refactored # TODO - is this appropriate behavior, or are references in YAML files acceptable, they are certainly less human readable self.current_table.data = {'independent_variables': [{'hea...
self.current_table.yheaders[i] if i < len(self.current_table.yheaders) else copy.deepcopy(self.current_table.yheaders[-1]), 'qualifiers': [self.current_table.qualifiers[j][i] if i < len(self.current_table.qualifiers[j]) else copy.deepcopy(self.current_table.qualifiers[j][-1]) for j in range(len(self.current_table.quali...
not line.startswith('*'): data_entry_elements = line.split(';')[:-1] # split and also strip newline character at the end if len(data_entry_elements) == len(header): # this is kind of a big stretch... I assume that x is always first for i, h in enumerate(header): single_element = data_entry_elements[i].strip() # number ...
pmnum1 + '|' + pmnum2 + '|' + pmnum3 + ')' # implement same regular expression matching as in old subs.pl parsing script if h == 'x': # independent variables r = re.search('^(?P<value>' + pmnum + ')$', single_element) if r: # "value" single_element = {'value': r.group('value')} else: r = re.search('^(?P<value>' + pmnum...
if r: # "value (BIN=low TO high)" single_element = {'value': float(r.group('value')), 'low': float(r.group('low')), 'high': float(r.group('high'))} else: r = re.search('^(?P<low>' + pmnum + ')\s+TO\s+(?P<high>' + pmnum + ')$', single_element) if r: # "low TO high" single_element = {'low': float(r.group('low')), 'high':...
"low high", "value low high" (sorted), # "value +- err", and "value -err_m, +err_p". Do we need to support these formats here? # Probably not: unsupported formats will just be written as a text string. self.current_table.data['independent_variables'][xy_mapping[i]]['values'].append(single_element) # extract energy if S...
self.set_of_energies.add(energy) except: pass elif h == 'y': # dependent variable pmnum_pct = pmnum + '(\s*PCT)?' # errors can possibly be given as percentages r = re.search('^(?P<value>' + pmnum + ')\s+(?P<err_p>' + pmnum_pct + '|-)\s*,\s*(?P<err_m>' + pmnum_pct + '|-)\s*(?P<err_sys>\(\s*DSYS=[^()]+\s*\))?$', single_e...
missing error as '-' in oldhepdata format err_p = err_p[:-3].strip() + '%' if err_p[-3:] == 'PCT' else err_p err_m = r.group('err_m').strip().lstrip('+') if err_m == '-': err_m = '' # represent missing error as '-' in oldhepdata format err_m = err_m[:-3].strip() + '%' if err_m[-3:] == 'PCT' else err_m if err_p and err_...
'%' if not err_p and not err_m: raise ValueError("Both asymmetric errors cannot be '-': %s" % line) if r.group('err_sys'): element['errors'] += [{'label': 'stat', 'asymerror': {'plus': err_p, 'minus': err_m}}] else: element['errors'] += [{'asymerror': {'plus': err_p, 'minus': err_m}}] else: r = re.search('^(?P<value>' ...
= error[:-3].strip() + '%' if error[-3:] == 'PCT' else error if r.group('err_sys'): element['errors'] += [{'label': 'stat', 'symerror': error}] else: element['errors'] += [{'symerror': error}] else: # everything else element['value'] = single_element err_sys = [] if r and r.group('err_sys'): err_sys = r.group('err_sys'...
+ pmnum_pct + ')\s*(\:\s*(?P<label>.+))?$', err) if r: # symmetric systematic error if r.group('label'): label += ',' + r.group('label') error = r.group('error').strip().lstrip('+') error = error[:-3].strip() + '%' if error[-3:] == 'PCT' else error error = {'symerror': error} else: r = re.search('^(?P<err_p>' + pmnum_p...
r.group('err_p').strip().lstrip('+') if err_p == '-': err_p = '' # represent missing error as '-' in oldhepdata format err_p = err_p[:-3].strip() + '%' if err_p[-3:] == 'PCT' else err_p err_m = r.group('err_m').strip().lstrip('+') if err_m == '-': err_m = '' # represent missing error as '-' in oldhepdata format err_m =...
!= '%' and err_m[-1] == '%': err_p = err_p + '%' if not err_p and not err_m: raise ValueError("Both asymmetric errors cannot be '-': %s" % line) error = {'asymerror': {'plus': err_p, 'minus': err_m}} if not r: # error happened raise ValueError("Error while parsing data line: %s" % line) error['label'] = label if elemen...
elements but %s expected: %s" % (len(data_entry_elements), len(header), line)) last_index = self.current_file.tell() l = self.current_file.readline() line = self._strip_comments(l) self.current_file.seek(last_index) # extract minimum and maximum from set of energies if self.set_of_energies: energy_min = min(self.set_of...
reformatted = self._reformat_matrix()
def _reformat_matrix(self): """Transform a square matrix into a format with two independent variables and one dependent variable. """ nxax = len(self.current_table.data['independent_variables']) nyax = len(self.current_table.data['dependent_variables']) npts = len(self.current_table.data['dependent_variables'][0]['valu...
if len(self.current_table.xheaders) == 2: xheader = self.current_table.xheaders[1] else: xheader = copy.deepcopy(self.current_table.data['independent_variables'][0]['header']) self.current_table.data['independent_variables'].append({'header': xheader, 'values': []}) for value in self.current_table.data['independent_var...
qualifier if different for second y-axis iqdel = [] # list of qualifier indices to be deleted for iq, qualifier in enumerate(self.current_table.data['dependent_variables'][0]['qualifiers']): if qualifier != self.current_table.data['dependent_variables'][1]['qualifiers'][iq]: iqdel.append(iq) for iq in iqdel[::-1]: # ne...
delete the second and subsequent y-axes in reverse order for iy in range(nyax-1, 0, -1): del self.current_table.data['dependent_variables'][iy] return True
def _parse_qual(self, data): """Parse qual attribute of the old HEPData format example qual: *qual: RE : P P --> Z0 Z0 X :param data: data to be parsed :type data: str """ list = [] headers = data.split(':') name = headers[0].strip() name = re.split(' IN ', name, flags=re.I) # ignore case units = None if len(name) > 1:...
if len(headers) < 2: raise BadFormat("*qual line must contain a name and values: %s" % data) for header in headers[1:]: xheader = {'name': name} if units: xheader['units'] = units xheader['value'] = header.strip() list.append(xheader) # extract energy if SQRT(S) is one of the qualifiers if name.startswith('SQRT(S)') an...
self.set_of_energies.add(energy) except: pass self.current_table.qualifiers.append(list)
def _parse_header(self, data): """Parse header (xheader or yheader) :param data: data to be parsed :type data: str :return: list with header's data :rtype: list """ return_list = [] headers = data.split(':') for header in headers: header = re.split(' IN ', header, flags=re.I) # ignore case xheader = {'name': header[0]....
def _strip_comments(line): """Processes line stripping any comments from it :param line: line to be processed :type line: str :return: line with removed comments :rtype: str """ if line == '': return line r = re.search('(?P<line>[^#]*)(#(?P<comment>.*))?', line) if r: line = r.group('line') if not line.endswith('\n'): ...
def _read_multiline(self, init_data): """Reads multiline symbols (ususally comments) :param init_data: initial data (parsed from the line containing keyword) :return: parsed value of the multiline symbol :rtype: str """ result = init_data first = True while True: last_index = self.current_file.tell() line_raw = self.cu...
appropriate behavior? data = self._strip_comments(line_raw) # EOF, stop here if not data: break # we arrived to the next command, step back and break if len(data.strip()) >= 1 and data.strip()[0] == '*': self.current_file.seek(last_index) break if first: result += '\n' first = False result += data result = result.strip...
def _bind_set_table_metadata(self, key, multiline=False): """Returns parsing function which will parse data as text, and add it to the table metatadata dictionary with the provided key :param key: dictionary key under which parsed data will be added to table.metadata :type key: str :param multiline: if True this attrib...
Function """ def set_table_metadata(self, data): if multiline: data = self._read_multiline(data) if key == 'location' and data: data = 'Data from ' + data self.current_table.metadata[key] = data.strip() # method must be bound, so we use __get__ return set_table_metadata.__get__(self)
def _bind_parse_additional_data(self, key, multiline=False): """Returns parsing function which will parse data as text, and add it to the table additional data dictionary with the provided key :param key: dictionary key under which parsed data will be added to table.metadata :type key: str :param multiline: if True thi...
:rtype: Function """ def _set_additional_data_bound(self, data): """Concrete method for setting additional data :param self: :type self: OldHEPData """ # if it's multiline, parse it if multiline: data = self._read_multiline(data) if key not in self.additional_data: self.additional_data[key] = [] self.additional_data[ke...
def error_value_processor(value, error): """ If an error is a percentage, we convert to a float, then calculate the percentage of the supplied value. :param value: base value, e.g. 10 :param error: e.g. 20.0% :return: the absolute error, e.g. 12 for the above case. """ if isinstance(error, (str, unicode)): try: if "%" ...
elif error == "": error = 0.0 else: error = float(error) except: pass return error
def get_file_details(filepath, hash_algorithms=['sha256']): """ <Purpose> To get file's length and hash information. The hash is computed using the sha256 algorithm. This function is used in the signerlib.py and updater.py modules. <Arguments> filepath: Absolute file path of a file. hash_algorithms: <Exceptions> secure...
# Making sure that the format of 'filepath' is a path string. # 'securesystemslib.exceptions.FormatError' is raised on incorrect format. securesystemslib.formats.PATH_SCHEMA.check_match(filepath) securesystemslib.formats.HASHALGORITHMS_SCHEMA.check_match(hash_algorithms) # The returned file hashes of 'filepath'. file_h...
hash of the file. for algorithm in hash_algorithms: digest_object = securesystemslib.hash.digest_filename(filepath, algorithm) file_hashes.update({algorithm: digest_object.hexdigest()}) # Performing a format check to ensure 'file_hash' corresponds HASHDICT_SCHEMA. # Raise 'securesystemslib.exceptions.FormatError' if th...
def ensure_parent_dir(filename): """ <Purpose> To ensure existence of the parent directory of 'filename'. If the parent directory of 'name' does not exist, create it. Example: If 'filename' is '/a/b/c/d.txt', and only the directory '/a/b/' exists, then directory '/a/b/c/d/' will be created. <Arguments> filename: A path...
'filename' does not exist. <Return> None. """ # Ensure 'filename' corresponds to 'PATH_SCHEMA'. # Raise 'securesystemslib.exceptions.FormatError' on a mismatch. securesystemslib.formats.PATH_SCHEMA.check_match(filename) # Split 'filename' into head and tail, check if head exists. directory = os.path.split(filename)[0] ...
def file_in_confined_directories(filepath, confined_directories): """ <Purpose> Check if the directory containing 'filepath' is in the list/tuple of 'confined_directories'. <Arguments> filepath: A string representing the path of a file. The following example path strings are viewed as files and not directories: 'a/b/c'...
either the empty string or in 'confined_paths'; False, otherwise. """ # Do the arguments have the correct format? # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch. securesystemslib.formats.RELPATH_SCHEMA.check_match(filepath) securesystemslib.formats.RELPATHS_SCHEMA.check_match(confined_director...
to account for up-level references, etc. # TUF clients have the option of setting the list of directories in # 'confined_directories'. filepath = os.path.normpath(filepath) confined_directory = os.path.normpath(confined_directory) # A TUF client may restrict himself to specific directories on the # remote repository. T...
from. if os.path.dirname(filepath) == confined_directory: return True return False
def find_delegated_role(roles, delegated_role): """ <Purpose> Find the index, if any, of a role with a given name in a list of roles. <Arguments> roles: The list of roles, each of which must have a 'name' attribute. delegated_role: The name of the role to be found in the list of roles. <Exceptions> securesystemslib.exc...
side effects. <Returns> The unique index, an interger, in the list of roles. if 'delegated_role' does not exist, 'None' is returned. """ # 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 # 'secur...
index of a role, if any, with the same name. role_index = None for index in six.moves.xrange(len(roles)): role = roles[index] name = role.get('name') # This role has no name. if name is None: no_name_message = 'Role with no name.' raise securesystemslib.exceptions.RepositoryError(no_name_message) # Does this role have ...
is the only known role with the same name. if role_index is None: role_index = index # ...there are at least two roles with the same name. else: duplicate_role_message = 'Duplicate role (' + str(delegated_role) + ').' raise securesystemslib.exceptions.RepositoryError( 'Duplicate role (' + str(delegated_role) + ').') # ...
def ensure_all_targets_allowed(rolename, list_of_targets, parent_delegations): """ <Purpose> Ensure that the list of targets specified by 'rolename' are allowed; this is determined by inspecting the 'delegations' field of the parent role of 'rolename'. If a target specified by 'rolename' is not found in the delegations...
not raise an exception if 'rolename' is 'targets'. Targets allowed are either exlicitly listed under the 'paths' field, or implicitly exist under a subdirectory of a parent directory listed under 'paths'. A parent role may delegate trust to all files under a particular directory, including files in subdirectories, by s...
are also validated (i.e., its calculated path hash prefix must be delegated by the parent role). TODO: Should the TUF spec restrict the repository to one particular algorithm when calcutating path hash prefixes (currently restricted to SHA256)? Should we allow the repository to specify in the role dictionary the algori...
targets must be verified. This is a role name and should not end in '.json'. Examples: 'root', 'targets', 'targets/linux/x86'. list_of_targets: The targets of 'rolename', as listed in targets field of the 'rolename' metadata. 'list_of_targets' are target paths relative to the targets directory of the repository. The de...
parent delegations of 'rolename'. The metadata object stores the allowed paths and path hash prefixes of child delegations in its 'delegations' attribute. <Exceptions> securesystemslib.exceptions.FormatError: If any of the arguments are improperly formatted. securesystemslib.exceptions.ForbiddenTargetError: If the targ...
delegation to 'rolename'. <Side Effects> None. <Returns> None. """ # 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 any are improperly formatted. s...
target file listed in 'targets' is allowed. if rolename == 'targets': return # The allowed targets of delegated roles are stored in the parent's metadata # file. Iterate 'list_of_targets' and confirm they are trusted, or their # root parent directory exists in the role delegated paths, or path hash # prefixes, of the p...
'parent_delegations'. roles = parent_delegations['roles'] role_index = find_delegated_role(roles, rolename) # Ensure the delegated role exists prior to extracting trusted paths from # the parent's 'paths', or trusted path hash prefixes from the parent's # 'path_hash_prefixes'. if role_index is not None: role = roles[ro...
have lenth # greater than zero due to the format check above. if not consistent(actual_child_targets, allowed_child_path_hash_prefixes): message = repr(rolename) + ' specifies a target that does not' + \ ' have a path hash prefix listed in its parent role.' raise securesystemslib.exceptions.ForbiddenTargetError(message...
under role['paths'], otherwise raise an # exception. If the parent role explicitly lists target file paths in # 'paths', this loop will run in O(n^2), the worst-case. The repository # maintainer will likely delegate entire directories, and opt for # explicit file paths if the targets in a directory are delegated to # d...
fnmatch.fnmatch(child_target, allowed_child_path): break else: raise securesystemslib.exceptions.ForbiddenTargetError( 'Role ' + repr(rolename) + ' specifies' ' target' + repr(child_target) + ',' + ' which is not an allowed' ' path according to the delegations set by its parent role.') else: # 'role' should have been v...
case this clause is reached. raise securesystemslib.exceptions.FormatError(repr(role) + ' did not' ' contain one of the required fields ("paths" or' ' "path_hash_prefixes").') # Raise an exception if the parent has not delegated to the specified # 'rolename' child role. else: raise securesystemslib.exceptions.Repositor...
def paths_are_consistent_with_hash_prefixes(paths, path_hash_prefixes): """ <Purpose> Determine whether a list of paths are consistent with their alleged path hash prefixes. By default, the SHA256 hash function is used. <Arguments> paths: A list of paths for which their hashes will be checked. path_hash_prefixes: The l...
Effects> No known side effects. <Returns> A Boolean indicating whether or not the paths are consistent with the hash prefix. """ # 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 # 'securesystems...
'paths' and 'path_hash_prefixes' are inconsistent until # proven otherwise. consistent = False # The format checks above ensure the 'paths' and 'path_hash_prefix' lists # have lengths greater than zero. for path in paths: path_hash = get_target_hash(path) # Assume that every path is inconsistent until proven otherwise....
matching path_hash_prefix. Stop looking further. if not consistent: break return consistent
def get_target_hash(target_filepath): """ <Purpose> Compute the hash of 'target_filepath'. This is useful in conjunction with the "path_hash_prefixes" attribute in a delegated targets role, which tells us which paths it is implicitly responsible for. The repository may optionally organize targets into hashed bins to ea...
<Arguments> target_filepath: The path to the target file on the repository. This will be relative to the 'targets' (or equivalent) directory on a given mirror. <Exceptions> None. <Side Effects> None. <Returns> The hash of 'target_filepath'. """ # Does 'target_filepath' have the correct format? # Ensure the arguments ha...
named. # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch. securesystemslib.formats.RELPATH_SCHEMA.check_match(target_filepath) # Calculate the hash of the filepath to determine which bin to find the # target. The client currently assumes the repository uses # 'HASH_FUNCTION' to generate hashes an...
def import_json(): """ <Purpose> Tries to import json module. We used to fall back to the simplejson module, but we have dropped support for that module. We are keeping this interface intact for backwards compatibility. <Arguments> None. <Exceptions> ImportError: on failure to import the json module. <Side Effects> Non...
module = __import__('json') # The 'json' module is available in Python > 2.6, and thus this exception # should not occur in all supported Python installations (> 2.6) of TUF. except ImportError: #pragma: no cover raise ImportError('Could not import the json module') else: _json_module = module return module
def load_json_string(data): """ <Purpose> Deserialize 'data' (JSON string) to a Python object. <Arguments> data: A JSON string. <Exceptions> securesystemslib.exceptions.Error, if 'data' cannot be deserialized to a Python object. <Side Effects> None. <Returns> Deserialized object. For example, a dictionary. """ deserial...
to a Python object: ' + repr(data) raise securesystemslib.exceptions.Error(message) else: return deserialized_object
def load_json_file(filepath): """ <Purpose> Deserialize a JSON object from a file containing the object. <Arguments> filepath: Absolute path of JSON file. <Exceptions> securesystemslib.exceptions.FormatError: If 'filepath' is improperly formatted. securesystemslib.exceptions.Error: If 'filepath' cannot be deserialized ...
is a path string. # securesystemslib.exceptions.FormatError is raised on incorrect format. securesystemslib.formats.PATH_SCHEMA.check_match(filepath) deserialized_object = None # The file is mostly likely gzipped. if filepath.endswith('.gz'): logger.debug('gzip.open(' + str(filepath) + ')') fileobject = six.StringIO(gz...
deserialized_object finally: fileobject.close()