Example #1
0
    def _user_encrypt(self, file):
        """Encrypt file with given key

        This function encrypt accounts.yml file.

        Args:
            file (str): Encrypted file name.
        """
        pswd = self.__conf['credential']['password']
        key = self.__conf['credential']['key']

        file_org = file
        file_enc = file_org + '-encrypted'
        file_crd = file_org + '-credential'

        if os.path.exists(file_org):
            with open(file_org, 'rb') as fp_in:
                data = fp_in.read()

            with open(file_enc, 'wb', buffering=0) as fp_out:
                fernet = Fernet(key)
                encrypted = fernet.encrypt(data)
                fp_out.write(encrypted)

            with open(file_crd, 'w', buffering=1) as fp_out:
                fp_out.write('# password should be deleted!\n')
                fp_out.write('# password: "******"\n'.format(pswd.decode()))
                fp_out.write('key: "{}"\n'.format(key.decode()))
        else:
            raise IHEFileError(file_org) from None
Example #2
0
    def _user(self):
        """Get user information

        This is the main function to configure user's credentials.

        **Don't synchronize the details to github.**

        - File to read: ``accounts.yml-credential``
        - File to read: ``accounts.yml-encrypted``
        """
        conf_enc = None
        fname_org = self.__conf['file']
        fname_enc = self.__conf['credential']['file_enc']
        fname_crd = self.__conf['credential']['file_crd']
        file_org = os.path.join(self.__conf['path'], fname_org)
        file_enc = os.path.join(self.__conf['path'], fname_enc)
        file_crd = os.path.join(self.__conf['path'], fname_crd)

        if os.path.exists(file_org):
            conf_enc = yaml.load(open(file_org, 'r', encoding='UTF8'),
                                 Loader=yaml.FullLoader)
        else:
            conf_enc = None

        if conf_enc is None:
            if os.path.exists(file_enc):
                self._user_key(file_crd)

                conf_enc = yaml.load(self._user_decrypt(file_enc),
                                     Loader=yaml.FullLoader)
            else:
                self.__status['code'] = 1
                raise IHEFileError(file_enc) from None

        if conf_enc is not None and isinstance(conf_enc, dict):
            for key in conf_enc:
                try:
                    self.__conf['data'][key] = conf_enc[key]
                except KeyError:
                    self.__status['code'] = 1
                    raise IHEKeyError(key, fname_enc) from None
                else:
                    subkey = self.__conf['account']['name']
                    if subkey is not None:
                        try:
                            self.__conf['account']['data'] = conf_enc[key][subkey]
                        except KeyError:
                            raise IHEKeyError(subkey, fname_enc) from None
                        else:
                            self.__status['code'] = 0
                    else:
                        self.__conf['account']['name'] = ''
                        self.__status['code'] = 0

        self.set_status(
            inspect.currentframe().f_code.co_name,
            prt=self.__status['is_print'],
            ext='')
Example #3
0
    def generate_encrypt(self):
        """Generate encrypted files
        """
        fname_org = self.__conf['file']
        fname_enc = self.__conf['credential']['file_enc']
        fname_crd = self.__conf['credential']['file_crd']
        file_org = os.path.join(self.__conf['path'], fname_org)
        file_enc = os.path.join(self.__conf['path'], fname_enc)
        file_crd = os.path.join(self.__conf['path'], fname_crd)

        pswd = input('\33[91m'
                     'IHEWAcollect: Enter your password: '******'\33[0m')
        pswd = pswd.strip()

        if pswd == '' or pswd is None:
            print(IHEStringError('password'))
            sys.exit(1)
        else:
            self.__conf['credential']['password'] = str.encode(pswd)
            key = self._user_key_generator()

            if os.path.exists(file_org):
                with open(file_org, 'rb') as fp_in:
                    data = fp_in.read()

                with open(file_enc, 'wb', buffering=0) as fp_out:
                    fernet = Fernet(key)
                    encrypted = fernet.encrypt(data)
                    fp_out.write(encrypted)

                with open(file_crd, 'w', buffering=1) as fp_out:
                    fp_out.write('# password should be deleted!\n')
                    fp_out.write('# password: "******"\n'.format(pswd))
                    fp_out.write('key: "{}"\n'.format(key))
            else:
                raise IHEFileError(file_org) from None
Example #4
0
    def load_file(self, file, band=1) -> np.ndarray:
        """Get tif band data

        This function get tif band as numpy.ndarray.

        Args:
            file (str): 'C:/file/to/path/file.tif' or a gdal file (gdal.Open(file))
                string that defines the input tif file or gdal file.
            band (int): Defines the band of the tif that must be opened.

        Returns:
            :obj:`numpy.ndarray`: Band data.
        """
        data = np.ndarray

        ds = gdal.Open(file)
        if ds is None:
            raise IHEFileError(file) from None
        else:
            if band is None:
                band = 1
            # data = fp.GetRasterBand(band).ReadAsArray()

            if ds.RasterCount > 0:
                try:
                    ds_band = ds.GetRasterBand(band)
                    if ds_band is None:
                        pass
                    else:
                        ds_band_ndv = ds_band.GetNoDataValue()
                        ds_band_scale = ds_band.GetScale()
                        # ds_band_unit = ds_band.GetUnitType()

                        data = ds_band.ReadAsArray()

                        # Check data type
                        if isinstance(data, np.ma.MaskedArray):
                            data = data.filled()
                        else:
                            data = np.asarray(data)

                        # convert to float
                        data = data.astype(np.float32)

                        if np.logical_or(isinstance(ds_band_ndv, str),
                                         isinstance(ds_band_scale, str)):
                            ds_band_ndv = float(ds_band_ndv)
                            ds_band_scale = float(ds_band_scale)

                        # Convert units, set NVD
                        if ds_band_ndv is not None:
                            data[data == ds_band_ndv] = np.nan
                        if ds_band_scale is not None:
                            data = data * ds_band_scale

                except BaseException:
                    raise IHEKeyError('Band {b}'.format(b=band), file) from None
            else:
                raise IHEFileError(file) from None

        ds = None
        return data