在Python中加密文本文件,最好使用模块[关闭]

问题描述 投票:-2回答:3

Context:

我有一个班级,我必须在其中保护密码。 (我的讲师不是很具体。)我之所以要求使用标准导入语句的方法是因为我只能上传一个只包含文本文件和程序本身的文件夹。我想做点如下的事情:

#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();

Resolution:

Sasszem的答案是对我有用的答案。查看评论以获得主要答案的简化说明。给我他/她定制代码的人(我不记得谁给了我,对不起。)有一个好主意。但我不喜欢使用我不理解的代码。最后,给我加密模块作为一个想法的人并没有错,但我在Windows上使用python。

python encryption byte encode
3个回答
0
投票

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

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

如果您制作类似于程序的内容,则在将pwd播种到随机生成器之后生成随机数添加到字节中,您的教师将会留下深刻印象。

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


0
投票

cryptography提供加密/解密支持:https://pypi.python.org/pypi/cryptography。我知道它包含在Anaconda中。


0
投票

这是我前一段时间写的模块。它仅使用内置的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()
© www.soinside.com 2019 - 2024. All rights reserved.