加密 Python 中的文本文件,最好使用模块

Encrypting a Text File in Python, Preferably with a Module

上下文:

我有一个 class,我必须在其中设置密码保护某物或其他东西。
(我的导师不是很具体。)我要求使用标准导入语句的方法的原因是我可以只上传一个仅包含文本文件和程序本身的文件夹。我想做如下事情:

#Import Statements Here
outFile = open('myFile.txt',"wt");

#Here is the tricky part.
#In place of all of these comments,
#I want to encrypt the file with a key given by a user(in this case,givenKey):
givenKey = input("Please input your key:>>>");
outFile.close();

分辨率:

Sasszem 的回答对我有用。看看评论 对于主要答案的简化解释。给我 his/her 定制代码的人(我不记得是谁给我的,对不起。)有一个好主意。但我不喜欢使用我不理解的代码。最后,给我 Cryptography 模块作为想法的人没有错,但我在 Windows 上使用 python。

程序包 cryptography 提供对 encryption/decryption 的支持:https://pypi.python.org/pypi/cryptography。我知道它包含在 Anaconda 中。

这是我不久前写的一个模块。它仅使用内置 python 模块。我允许你使用它!

import string, random

class Round(object):
    def __init__(self, *seqs):
        self.position = 0
        self.data = [i for x in seqs for i in x]
        self.len = len(self.data)

    def __repr__(self):
        return str(self.data)

    def __iter__(self):
        self.position = 0
        return self

    def is_item(self, item):
        if str(self.data[self.position]) == str(item):
            return True
        return False

    def __getitem__(self, index):
        if index < self.len-1 and index >= 0:
            return self.data[index]
        else:
            while index < 0:
                index += self.len-1
            while index > self.len-1:
                index -= self.len-1
            return self.data[index]

    def next(self):
        if self.position >= self.len-1:
            self.position = 0
            raise StopIteration
        else:
            self.position += 1
            return self.data[self.position-1]

class JCripter(object):
    def __init__(self, string):
        self.string = string
        self.generate_key_set()
        self.encrypted = False

    def generate_key_set(self):
        self.alphabet = list(string.ascii_lowercase)
        self.numbers = [str(x) for x in range(10)]
        self.special_characters = ['"',"'",',','?','.',
                                   ' ','(',')',':',';',
                                   '!','@','#','$','%',
                                   '^','&','*','_','-',
                                   '+','=','<','>','~',
                                   '`','{','[','}',']',
                                   '\','|']
        self.key_base = Round(self.alphabet, self.numbers, self.special_characters)

    def get_key_index(self, key):
        for i in self.key_base:
            if isinstance(key, int):
                if i == self.key_base[key]:
                    return self.key_base.position-1
            elif i == key.lower():
                return self.key_base.position-1
        else:
            print 'not found'

    def __repr__(self):
        return self.string

    def _encrypt(self, string, func, *args):
        if string == None:
            string = self.string
            if string == None:
                return
        string = string.lower()
        n_string = func(string, *args)
        self.encrypted = not self.encrypted
        self.string = n_string
        return n_string

class CeaserCypher(JCripter):
    def __init__(self, string, shift=None):
        JCripter.__init__(self, string)
        if shift == None:
            self.shift = random.randint(0, self.key_base.len)
        else:
            self.shift = shift

    def encrypt(self, string=None):
        def inner(string):
            n_string=''
            for i in string:
                if self.encrypted == True:
                    n_string += self.key_base[self.get_key_index(i)-self.shift]
                else:
                    n_string += self.key_base[self.get_key_index(i)+self.shift]
            return n_string
        return self._encrypt(string, inner)

class PseudoRandomCypher(JCripter):
    def __init__(self, string, shifts=None):
        if shifts == None:
            self.shift = [random.randint(0, 500) for x in string]
        else:
            self.shift = shifts
        JCripter.__init__(self, string)

    def encrypt(self, string=None):
        def inner(string):
            ind = 0
            n_string = ''
            for i in string:
                if ind >= len(self.shift)-1:
                    ind = 0
                if self.encrypted == True:
                    n_string += self.key_base[self.get_key_index(i)-self.shift[ind]]
                else:
                    n_string += self.key_base[self.get_key_index(i)+self.shift[ind]]
                ind += 1
            return n_string

        return self._encrypt(string, inner)

class PolyAlphabeticCypher(JCripter):
    def __init__(self, string, key, enc=False):
        JCripter.__init__(self, string)
        self.key=list(key)
        self.encrypted = enc

    def encrypt(self, string=None):
        def inner(string):
            index = 0
            n_string = ''
            for i in string:
                if index >= len(self.key)-1:
                    index = 0
                if self.encrypted == True:
                    n_string += self.key_base[self.get_key_index(i)-self.get_key_index(self.key[index])]
                else:
                    n_string += self.key_base[self.get_key_index(i)+self.get_key_index(self.key[index])]
                index += 1
            return n_string
        return self._encrypt(string, inner)


n = 'Hello world my name is anonymous!'
p = PolyAlphabeticCypher(n, 'super_secret_password')
print p.encrypt() #--> returns encrypted data
print p.encrypt() #--> decrypts data


#if you are decrypting a previously encrypted text

n = 'Some sensitive data'
first = PolyAlphabeticCypher(n, 'some pass')
my_data = first.encrypt()
second = PolyAlphabeticCypher(my_data, 'some pass', True)
print second.encrypt()

加密数据的一种简单方法是为每个字节添加一个常量

您可以从密码生成一些随机字节,然后将其添加到输入中的每个字节。它不会很强,但很简单。

如果在将密码播种到随机生成器后,您的程序会生成随机数以添加到字节中,您的讲师将会印象深刻。

要解码,只需从字节中减去相同的数字即可。