gpt4 book ai didi

Python - 使用翻转密码对文件进行编码

转载 作者:太空宇宙 更新时间:2023-11-03 18:40:30 25 4
gpt4 key购买 nike

我正在尝试使用翻转密码对文件进行编码。我编写了一个程序来对字符串进行编码,并且它可以在普通字符串上运行。我编写了另一个程序来读取文件,将其编码为 block ,然后将其写入输出文件。它在 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()

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

最佳答案

输入文件包含 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

关于Python - 使用翻转密码对文件进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20602649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com