def getKeyValue(keyName):
     key = message.prompt(keyName + ' value')
     if (key != ''):
         dictkeys[keyName] = key
     elif (key == ''):
         message.error('Value cannot be empty.')
         getKeyValue(keyName)
예제 #2
0
파일: file.py 프로젝트: Vinesma/.dotfiles
    def link(self):
        """Link this file from source to destination"""

        if self.path_source is not None:
            full_source_path = os.path.join(
                os.path.expandvars(self.path_source), self.name)
            full_destination_path = os.path.join(
                os.path.expandvars(self.path_destination), self.name)

            try:
                if self.sudo:
                    spawn.process(
                        f'ln -sfv "{full_source_path}" "{full_destination_path}"',
                        sudo=True,
                    )
                else:
                    os.symlink(full_source_path, full_destination_path)
            except FileExistsError:
                message.error(
                    "Can't symlink, file already exists at destination. Attempting fix."
                )
                os.remove(full_destination_path)
                message.info(f"Removed: '{full_destination_path}'")
                os.symlink(full_source_path, full_destination_path)
            finally:
                message.info(
                    f"Symlink created: '{full_source_path}' <--> '{full_destination_path}'"
                )
        else:
            message.error(
                f"'{self.name}' has no source from which to create a link from."
            )
def modify(fileName):
    dictkeys = jsonToDict(fileName)

    def modifyKeyValue(keyName):
        if keyName in dictkeys:
            key = message.prompt(keyName + ' new value')
            if (key != ''):
                dictkeys[keyName] = key
            elif (key == ''):
                message.error('Value cannot be empty.')
                getKeyValue(keyName)

        else:
            message.error('No such Key exists!')

    while (True):
        keyName = message.prompt('Enter Key to be modified (done)')
        if (keyName != ''):
            modifyKeyValue(keyName)
        elif (keyName == ''):
            break

    try:
        dictToJson(dictkeys, fileName)
        message.success('Keys modified successfully!')
    except:
        message.error('Some error occured!')
        return False


#test functions

#add(fileName)
#subtract(fileName)
#modify(fileName)
예제 #4
0
def generate_encryption():
    key = keygen()

    #Displaying the Key
    message.success("SECURITY KEY GENERATED: " + key)
    user_choice = message.prompt("Save the key locally (Y/n)")

    # user choice to save the file
    # default user choice is YES
    if user_choice == "" or user_choice.lower() == "y" or user_choice.lower(
    ) == "yes":
        storage_choice = message.prompt(
            "Path to store key to (" + os.path.join(STORAGE_DIR, STORE_KEY_F) +
            "_keys.key" + ")")
        if storage_choice != "":
            storeKey(key, storage_choice)
        else:
            storeKey(key)
            print(key)
    elif user_choice.lower() == "n" or user_choice.lower() == "no":
        message.success("YOUR KEY WILL NOT BE STORED. KEEP IT SAFE.")
    else:
        message.error("INVALID INPUT")
        generateEncryption()
    return key
예제 #5
0
def display_json(filename, display_indent=4):
    json_val = jsonToDict(filename)
    if json_val:
        message.success(filename + ' loaded successfully')
        printy(json_val, indentation=display_indent)
    else:
        message.error('JSON couldn\'t be loaded')
        debug.error('JSON to Dict Failed')
예제 #6
0
def main_menu(args):
    # print(args)
    if args[0].lower() == 'init':
        init_function()
    elif args[0].lower() == '--help':
        help()
    elif args[0].lower() == '--version':
        version()
    else:
        fname = args[0]
        cmd = args[1]

        # encrypt file
        if cmd.lower() == 'enc':
            if checkEnc(fname) != False:
                keyFname = message.prompt('File with key for description (' +
                                          STORAGE_DIR + '/' + STORE_KEY_F +
                                          '): ')
                key = getKey() if keyFname == '' else getKey(keyFname)
                encryption(key, fname)
                message.success(fname + ' is now encrypted')
            else:
                message.error(fname + ' is already encrypted')

        # decrypt file
        elif cmd.lower() == 'dec':
            if checkEnc(fname) != False:
                message.error(fname + ' is already decrypted')
            else:
                keyFname = message.prompt('File with key for description (' +
                                          STORAGE_DIR + '/' + STORE_KEY_F +
                                          '): ')
                key = getKey() if keyFname == '' else getKey(keyFname)
                decryption(key, fname)
                message.success(fname + ' is now decrypted')

        # add new keys
        elif cmd.lower() == 'add':
            if checkEnc(fname) != False:
                add(fname)
            else:
                message.error(fname + ' is encrypted')

        # subtract keys
        elif cmd.lower() == 'sub':
            if checkEnc(fname) != False:
                subtract(fname)
            else:
                message.error(fname + ' is encrypted')

        # subtract keys
        elif cmd.lower() == 'mod':
            if checkEnc(fname) != False:
                modify(fname)
            else:
                message.error(fname + ' is encrypted')
예제 #7
0
def keygen():
    try:
        #generating the key and storing them in a file
        key = Fernet.generate_key()
        message.success("Encryption key generated successfully")
    except Exception as e:
        message.error('Couldn\'t generate encryption key')
        debug.error(str(e))
        return False
    return key.decode('utf-8')
예제 #8
0
def dictToJson(inputDict, filename, indents=2):
    try:
        with open(filename, 'w') as fh2:
            fh2.write(json.dumps(inputDict, indent=indents, sort_keys=True))
        message.success('Keys stored successfully')
        return True
    except Exception as e:
        message.error('Couldn\'t write to JSON')
        debug.error(str(e))
        return False
예제 #9
0
파일: spawn.py 프로젝트: Vinesma/.dotfiles
def process(process_string, silent=False, capture=False, sudo=False):
    """Run a process.

    If silent = False, displays process output to the screen,
    otherwise only this program's output is shown.

    If capture = True, return the process' stdout instead of a CompletedProcess instance.

    If sudo = True, run the process as super user
    (may require user intervention for collecting password).

    On error, stops execution for 30 seconds for evaluation, alternatively, crashes the program.
    """

    if sudo:
        process_string = f"{config.admin_command} {process_string}"

    [process_name, *args] = process_string.split()

    # Remove special {SPACE} character, which denotes a space that doesn't mean a new argument
    for index, arg in enumerate(args):
        if "{SPACE}" in arg:
            args[index] = arg.replace("{SPACE}", " ")

    try:
        output = run(
            [process_name, *args],
            check=True,
            text=True,
            capture_output=(capture or silent),
        )
    except CalledProcessError as error:
        message.error(
            f"'{process_name}' failed with code {error.returncode} :: {error.output}"
        )
        message.alert(f"ARGS: {args}")

        if config.fail_fast:
            message.alert(
                f"Halting execution because of fail_fast = {config.fail_fast}")
            sys.exit(1)
        else:
            message.info("Stopping execution temporarily for your evaluation.")

            for i in range(3, 0, -1):
                message.info(f"Program will continue in {i * 10} seconds...")
                sleep(config.seconds_to_wait_on_fail)

            output = run(["echo"], check=True, text=True)

    if capture:
        return output.stdout

    return output
    def modifyKeyValue(keyName):
        if keyName in dictkeys:
            key = message.prompt(keyName + ' new value')
            if (key != ''):
                dictkeys[keyName] = key
            elif (key == ''):
                message.error('Value cannot be empty.')
                getKeyValue(keyName)

        else:
            message.error('No such Key exists!')
예제 #11
0
def decryption(key, filename):
    try:
        with open(filename,'rb') as f:
            data = f.read()
        q = Fernet(key)
        decrypted_message = q.decrypt(data)
        with open(filename,'wb') as f:
            f.write(decrypted_message)
        message.success(filename + ' successfully decrypted')
    except Exception as e:
        message.error(filename + ' couldn\'t be decrypted')
        debug.error(filename + ' couldn\'t be decrypted')
        print(e)
        return False
    return True
예제 #12
0
def encryption(key, filename):
    try:
        with open(filename, 'rb') as f:
            data = f.read()
        #encrypting the data from the given file name
        fernet = Fernet(key)
        encrypted=fernet.encrypt(data)    
        with open(filename,'wb') as f:
            f.write(encrypted)
        message.success(filename + ' successfully encrypted')
    except Exception as e:
        message.error(filename + ' couldn\'t be encrypted')
        debug.error(filename + ' couldn\'t be encrypted')
        print (e)
        return False
    return True
예제 #13
0
def storeKey(key, filename = STORE_KEY_F):
    storeTo = os.path.join (STORAGE_DIR, filename) + "_keys.key"
    if init_default_key_storage():
        try:
            #creating the key file in which the key'll be stored
            file = open(storeTo,'w')
            file.write(key)
            file.close()
            message.success("Key was stored to " + storeTo + " successfully")
        except Exception as e:
            message.error("Key couldn't be stored to " + storeTo)
            debug.error("Key couldn't be stored to " + storeTo)
            return False
        return True
    else:
        return False
예제 #14
0
def init_function():
    if init_default_key_storage():
        filename = get_filename_from_user()
        tokendict = get_keys_from_user()
        enc_key = generate_encryption()

        if dictToJson(tokendict, filename):
            if encryption(enc_key, filename):
                message.success("Filename: " + filename)
        else:
            message.error("Filename: " + filename)
        message.success("Keys Added: ")
        printy(tokendict, indentation=4)


# init_function()
예제 #15
0
def getKey(filename = STORE_KEY_F):
    getFrom = os.path.join (STORAGE_DIR, filename) + "_keys.key"
    if init_default_key_storage():
        try:
            # retriving key file
            file = open (getFrom, 'r')
            key = file.read ()
            file.close ()
            message.success ('Loaded encryption key successfully')
            return key
        except:
            message.error ('Couldn\'t load encryption key')
            debug.error ('Couldn\'t load encryption key')
            return False
    else:
        message.error ('Couldn\'t load encryption key')
        debug.error ('Couldn\'t load encryption key')
        return False
예제 #16
0
파일: file.py 프로젝트: Vinesma/.dotfiles
    def copy(self):
        """Copy this file from source to destination"""

        if self.path_source is not None:
            full_source_path = os.path.join(
                os.path.expandvars(self.path_source), self.name)

            if self.sudo:
                spawn.process(
                    f'cp -v -- "{full_source_path}" "{self.path_destination}"',
                    sudo=True,
                )
            else:
                message.info(
                    f"Copied: '{full_source_path}' --> '{self.path_destination}'"
                )
                shutil.copy(full_source_path, self.path_destination)
        else:
            message.error(
                f"'{self.name}' has no source from which to copy from.")
def subtract(fileName):
    dictkeys = jsonToDict(fileName)

    def removeKeyValue(keyName):
        try:
            del dictkeys[keyName]
        except:
            message.error('No such Key exists!')

    while (True):
        keyName = message.prompt('Enter Key to be removed (done)')
        if (keyName != ''):
            removeKeyValue(keyName)
        elif (keyName == ''):
            break

    try:
        dictToJson(dictkeys, fileName)
        message.success('Keys removed successfully!')
    except:
        message.error('Some error occured!')
        return False
예제 #18
0
파일: file.py 프로젝트: Vinesma/.dotfiles
    def touch(self):
        """Create this file at its destination. Write text to it."""
        full_destination_path = os.path.join(
            os.path.expandvars(self.path_destination), self.name)

        try:
            with open(full_destination_path, "w", encoding="utf-8") as _file:
                _file.write(self.text)
            message.info(
                f"Created file: '{self.name}' at '{self.path_destination}'")
        except OSError:
            message.error(
                f"There was a problem creating the file '{self.name}' at '{self.path_destination}'"
            )

            if config.fail_fast:
                sys.exit(1)

            message.info("Stopping execution temporarily for your evaluation.")

            for i in range(3, 0, -1):
                message.info(f"Program will continue in {i * 10} seconds...")
                sleep(config.seconds_to_wait_on_fail)
def add(fileName):
    dictkeys = jsonToDict(fileName)

    def getKeyValue(keyName):
        key = message.prompt(keyName + ' value')
        if (key != ''):
            dictkeys[keyName] = key
        elif (key == ''):
            message.error('Value cannot be empty.')
            getKeyValue(keyName)

    while (True):
        keyName = message.prompt('Key (done)')
        if (keyName != ''):
            getKeyValue(keyName)
        elif (keyName == ''):
            break
    try:
        dictToJson(dictkeys, fileName)
        message.success('New keys added successfully!')
    except:
        message.error('Some error occured!')
        return False
 def removeKeyValue(keyName):
     try:
         del dictkeys[keyName]
     except:
         message.error('No such Key exists!')