Python - 使用flip cipher编码文件

时间:2013-12-16 02:44:25

标签: python encoding

我正在尝试使用翻转密码对文件进行编码。我编写了一个编码字符串的程序,它已经处理了正常的字符串。我写了另一个程序来读取文件,用块编码,然后将其写入输出文件。它工作正常大约1MB,但后来我得到一个错误。无论我使用什么键字符串,我都会得到一个

TypeError: must be string or buffer, not None

我已经在编码函数本身写了一些错误检查,并且出现错误。这是我的代码,如果有人可以看看。

包含功能的文件:

class KeyString:
    def genNums(self):
        self.keys = {}
        i = 1
        for letter in self.chars:
            self.keys[letter] = i
            i += 1

    def __init__(self,chars='"LB}+h<=,.T->XcxzCdD*2Mo\RsSwj/NJ#F;kOZG!5(47Y9UrVn@%Aybul_m6ag$)pf3IEtQ{0W\'K:q1HP&^v8?i`[ ~]|e)'):
        self.chars = chars
        self.keys = {}
        self.genNums()

def encode(s,k,d=False):
    """ Encodes string 's' using string 'k' """
    if k == '': return s ## Makes it easier for Tribble
    elif not len(k) >= 10:
        print('[encd] - key too short')
        return s
    string = [ord(letter) for letter in s]
    ks = KeyString()
    try: key = [ks.keys[letter] for letter in k]
    except:
        print('[encd] - key not valid')
        return s
    length = len(string) - 1
    loc = 0
    for i in xrange(0,length):
        string[i] += key[loc]
        if string[i] > 256: string[i] -= 256
        loc += 1
        if loc == len(key): loc = 0
    loc = 0
    for i in xrange(0,length):        
        temp = 0
        if i + key[loc] > length: temp -= length
        else: temp = key[loc]
        string[i],string[i+temp] = string[i+temp],string[i]
        loc += 1
        if loc == len(key): loc = 0
    if d: print(s,'--->',''.join(chr(item) for item in string))
    try: return ''.join(chr(item) for item in string)
    except: print('Error - ords as follows: %s' % (','.join(str(item) for item in string)))

def decode(s,k,d=False):
    """ Decodes string 's' using string 'k' """
    if k == '': return s ## Makes it easier for Tribble
    if not len(k) >= 10:
        print('[decd] - key too short')
        return s
    string = [ord(letter) for letter in s]
    ks = KeyString()
    try: key = [ks.keys[letter] for letter in k]
    except:
        print('[decd] - key not valid')
        return s
    length = len(string) - 1
    loc = 0
    for i in xrange(0,length):
        loc += 1
        if loc == len(key): loc = 0
    loc -= 1
    if loc == -1: loc = len(key) - 1
    for i in reversed(xrange(0,length)):      
        temp = 0
        if i + key[loc] > length: temp -= length
        else: temp = key[loc]
        string[i],string[i+temp] = string[i+temp],string[i]
        loc -= 1
        if loc == -1: loc = len(key) - 1
    loc = 0
    for i in xrange(0,length):
        string[i] -= key[loc]
        if string[i] < 1: string[i] += 256
        loc += 1
        if loc == len(key): loc = 0
    if d: print(s,'--->',''.join(chr(item) for item in string))
    try: return ''.join(chr(item) for item in string)
    except: print('Error - ords as follows: %s' % (','.join(str(item) for item in string)))

class EncodeDecodeError(Exception):
    def __init__(self,s,k,x,y):
        self.s = s
        self.k = k
        self.x = x
        self.y = y

    def __str__(self):
        return repr('Encode/decode test failed on s=%s k=%s x=%s y=%s' % (self.s,self.k,self.x,self.y))

## The following just tests the encode/decode functions
## and raises an error if it fails
random.seed()

test = True
print('Running encode/decode test...')
for i in xrange(1,1000): ## len(str(i)) <= 5 is the important part
    s = str(random.randint(0,i))
    k = str(random.randint(1000000000,10000000000))
    x = encode(s,k,False)
    y = decode(x,k,False)
    if not y == s: raise EncodeDecodeError(s,k,x,y)
print('Done encode/decode test!')

在编码函数的某处出现错误。

这是文件加密程序:

import argparse
import sys
from os import path
from functools import partial

parser = argparse.ArgumentParser()
parser.add_argument('src',help='source file')
parser.add_argument('out',help='output file')
parser.add_argument('key',help='key to use')
parser.add_argument('-d','--decode',action='store_true',help='decode file')

args = parser.parse_args()

if not path.isfile(args.src):
    print 'Source file "%s" not found' % args.src
    sys.exit(1)

with open(args.src,'rb') as src:
    out = open(args.out,'wb')
    i = 0
    for chunk in iter(partial(src.read,1024),''):
        if not args.decode: x = encode(str(chunk),args.key)
        else: x = decode(str(chunk),args.key)
        out.write(x)
        print '%s kb' % (i)
        i += 1
    out.close()

我已经使用编码函数导入了文件,我只是在代码中将其导出。

1 个答案:

答案 0 :(得分:1)

输入文件包含0-255范围内的字节,而在 python2 中,chr函数只能返回该范围内的字符:

>>> chr(256)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(256)

您的代码中存在问题:

    if string[i] > 256: string[i] -= 256

,根据输入的不同,偶尔会允许string包含256(即有一个“一个一个”的错误)。所以,显然,修复它的方法很简单:

    if string[i] > 255: string[i] -= 255