Пример #1
0
def save_key(key, filepath):
    '''
    Save key to file

    :param key: Private Key
    :type key: RSA Private Key

    :param filepath: Destination filepath with filename
    :type filepath: str
    '''
    try:
        log.debug("Saving Private key to file: {}".format(filepath))
        key_bytes = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption())

        with open(filepath, "wb+") as f:
            f.write(key_bytes)
        log.debug("Key saved to file at location: {}".format(filepath))
        return True

    except FileError as file_err:
        log.debug(
            FileError('Error occurred while saving key to file {} '
                      'error: {} \n'.format(filepath, file_err)))
        log.error('Error: Failed to save key in file {}'.format(filepath))
    except Exception as err:
        log.debug(
            FileError('Error occurred while saving key to file {} '
                      'error: {} \n'.format(filepath, err)))
        log.error('Error: Failed to save key in file {}'.format(filepath))
Пример #2
0
def save_cert(cert, filepath):
    '''
    Save certificate to file

    :param cert: Certificate
    :type cert: x509 Certificate

    :param filepath: Destination filepath with filename
    :type filepath: str
    '''
    try:
        log.debug("Saving Certificate to file: {}".format(filepath))
        cert_bytes = cert.public_bytes(encoding=serialization.Encoding.PEM, )

        with open(filepath, "wb+") as f:
            f.write(cert_bytes)
        log.debug("Certificate saved to file {}".format(filepath))
        return True

    except FileError as file_err:
        log.debug(
            FileError('Error occurred while saving cert to '
                      'file {} error: {} \n'.format(filepath, file_err)))
        log.error('Error: Failed to save cert in file {}'.format(filepath))
    except Exception as err:
        log.debug("Error {}. Cannot save certificate".format(err))
        log.error('Error: Failed to save cert in file {}'.format(filepath))
Пример #3
0
def _save_nodeid_and_cert_to_file(node_id, dev_cert, dest_csv_file):
    '''
    Save Node Id and Certificate to file

    :param node_id: Node Id
    :type node_id: str

    :param dev_cert: Device Certificate
    :type dev_cert: x509 Certificate

    :param dest_csv_file: Destination CSV file
    :type dest_csv_file: str
    '''
    try:
        delimiter = ","
        newline = "\n"
        double_quote = "\""
        dev_cert_bytes = dev_cert.public_bytes(
            encoding=serialization.Encoding.PEM, )
        dev_cert_str = double_quote + dev_cert_bytes.decode('utf-8') + \
            double_quote
        log.debug("Saving node id and cert to file: {}".format(dest_csv_file))
        new_data = [node_id, dev_cert_str]
        data_to_write = delimiter.join(new_data) + newline
        dest_csv_file.write(data_to_write)
        log.debug("Node Id and Cert saved to file: {}".format(dest_csv_file))
        log.debug("Node id and certificate saved to file successfully")
        return True
    except FileError as file_err:
        log.error(
            FileError('Error occurred while saving node id and cert to '
                      'file {} error: {} \n'.format(dest_csv_file, file_err)))
    except Exception as err:
        log.error(
            FileError('Error occurred while saving node id and cert to '
                      'file {} error: {} \n'.format(dest_csv_file, err)))
        raise
Пример #4
0
    def read_config(self):
        '''
        Read from saved config file
        '''
        try:
            log.debug("Read from config file: {}".format(self.config_file))
            if not os.path.exists(self.config_file):
                log.debug('File not found: {}'.format(self.config_file))
                return None

            with open(self.config_file, "r") as config_file:
                user_config_data = json.load(config_file)

            log.debug("Config data received: {}".format(user_config_data))

            return user_config_data

        except Exception as err:
            log.error(FileError('Error occurred while reading config '
                                'from file {}\n{}'.format(
                                    self.config_file,
                                    err)))
            raise
Пример #5
0
def get_nodeid_from_file(filename):
    '''
    Get Node Id from file

    :param filename: Filename containing Node Ids
    :type filename: str
    '''
    try:
        log.debug("Getting node id from file: {}".format(filename))
        delimiter = ","
        with open(filename) as csvfile:
            rows_in_file = csvfile.readlines()
            file_data = _check_file_format(rows_in_file)
            log.debug("File data received: {}".format(file_data))
            nodeid_list = file_data[0].split(delimiter)
            log.debug("Node Ids list: {}".format(nodeid_list))
            nodeid_list = _check_file_format(nodeid_list)
            log.debug("Node Ids received from file: {}".format(nodeid_list))
            return nodeid_list
    except Exception as err:
        log.error(
            FileError('Error occurred while getting node ids from '
                      'file {}\n{}'.format(filename, err)))
        raise
Пример #6
0
def get_ca_cert_from_file(filename):
    '''
    Get CA Certificate from file

    :param filename: Filename for saving CA Certificate
    :type filename: str
    '''
    try:
        path_sep = os.sep
        filename = os.path.expanduser(filename.rstrip(path_sep))
        log.debug("Saving CA Certificate to file: {}".format(filename))
        ca_cert = None
        with open(filename, "rb") as crt_file:
            ca_cert = x509.load_pem_x509_certificate(crt_file.read(),
                                                     default_backend())
        log.debug("CA certificate from file received")
        return ca_cert
    except FileError as file_err:
        log.error(
            FileError('Error occurred while getting cert to '
                      'file {} error: {} \n'.format(filename, file_err)))
        return
    except Exception as err:
        raise Exception(err)
Пример #7
0
def get_ca_key_from_file(filename):
    '''
    Get CA Key from file

    :param filename: Filename for saving CA Private Key
    :type filename: str
    '''
    try:
        path_sep = os.sep
        filename = os.path.expanduser(filename.rstrip(path_sep))
        log.debug("Get CA Key from file: {}".format(filename))
        ca_key = None
        with open(filename, "rb") as key_file:
            ca_key = serialization.load_pem_private_key(
                key_file.read(), password=None, backend=default_backend())
        log.debug("CA Key received.")
        return ca_key
    except FileError as file_err:
        log.error(
            FileError('Error occurred while getting key to '
                      'file {} error: {} \n'.format(filename, file_err)))
        return
    except Exception as err:
        raise Exception(err)
Пример #8
0
def save_to_file(file_data,
                 output_dir,
                 filename_prefix=None,
                 dest_filename=None,
                 ext='.csv'):
    '''
    Save text data to file

    :param file_data: Data to save to file
    :type file_data: str

    :param output_dir: Output directory to store data
    :type output_dir: str

    :param filename_prefix: Prefix for Filename
    :type filename_prefix: str

    :param dest_filename: Name of destination file
    :type dest_filename: str
    '''
    file_mode = 'wb+'
    try:
        dest_filepath = None

        if not os.path.isdir(output_dir):
            os.makedirs(output_dir)
            log.debug("Directory created: {}".format(output_dir))

        if not dest_filename:
            dest_filepath = _set_filename(filename_prefix=filename_prefix,
                                          outdir=output_dir,
                                          ext=ext)
            if not dest_filepath:
                return None
        else:
            dest_filepath = os.path.join(output_dir, dest_filename)

        log.debug("Destination filename set: {}".format(dest_filepath))
        log.debug("Saving in output directory: {}".format(output_dir))

        # Write image to file (used for qrcode)
        if ext == '.png':
            with open(dest_filepath, 'wb+') as f:
                file_data.png(f, scale=4)
        else:
            try:
                # Write file data to file
                if not isinstance(file_data, bytes):
                    log.debug("Converting data to bytes")
                    file_data = file_data.encode('utf8')
            except AttributeError:
                log.debug("Converting data to json")
                file_data = json.dumps(file_data)
                file_mode = 'w+'

            log.debug("Writing data to file")
            with open(dest_filepath, file_mode) as f:
                try:
                    f.write(file_data)
                except TypeError:
                    f.write(file_data.decode('utf8'))

        return dest_filepath
    except Exception as err:
        log.error(
            FileError('Error occurred while saving node ids to '
                      'file {} error: {} \n'.format(dest_filepath, err)))
        raise