Skip to content Skip to sidebar Skip to footer

Obfuscating A String To Be Saved In A Text File

I am trying to obfuscate a string so that it is not easily read by users. However, the obfuscated string should be in form a string that can be stored in a text file, not in byte f

Solution 1:

def myencode_str(ori_str, key):
    enc = []
    for i in range(len(ori_str)):
        key_c = key[i % len(key)]
        enc_c = (ord(ori_str[i]) + ord(key_c)) % 256
        enc.append(enc_c)
    return (base64.urlsafe_b64encode(bytes(enc))).decode("utf-8") 

or see here for a full example:

from cryptography.fernet import Fernet

class Encrypt(object):
    '''
    see https://cryptography.io/en/latest/fernet/
    '''

    @classmethod
    def encrypt(cls, plain_text):
        '''
        @param enctypted_text: str or bytes
        @return cipher_text: str (.decode() converts the byte string to string)
        '''
        if isinstance(plain_text, str):
            plain_text = plain_text.encode()
        elif not isinstance(plain_text, bytes):
            raise ValueError('Value must be string or bytes')
        cipher_suite = Fernet(config.KEY.encode())
        cipher_text = cipher_suite.encrypt(plain_text).decode()
        return cipher_text

    @classmethod
    def decrypt(cls, enctypted_text):
        '''
        @param enctypted_text: str or bytes
        @return plain_text: str (.decode() converts the byte string to string)
        '''
        if isinstance(enctypted_text, str):
            enctypted_text = enctypted_text.encode()
        elif not isinstance(enctypted_text, bytes):
            raise ValueError('Value must be string or bytes')
        cipher_suite = Fernet(config.KEY.encode())
        plain_text = cipher_suite.decrypt(enctypted_text).decode()
        return plain_text

    @classmethod
    def generateKey(cls):
        key = Fernet.generate_key()
        return key*

Post a Comment for "Obfuscating A String To Be Saved In A Text File"