我正在尝试编写一个用于加密文件的基本算法。它获取字符串中每个字符的 ASCII 值,并根据密码的长度将其向上或向下移动一定的量,然后您可以在顶部分层更多密码。
def encrypt(s):
lenStr=s.__len__() #used later for working how far the int is moved
s=list(s) #converts the string to a list
for x in s:
s[x]=ord(s[x]) #the same index of the list is = to the value of the string
s[x]=chr(s[x])#is where it eventualy gets changed back to a str
s=ord(s)
是抛出错误的行,我在它周围添加了 int() 但没有帮助,同样的错误
最佳答案
您收到TypeError
异常,因为s[x]=ord(s[x])
中的x
值statements 是 s
列表的元素之一,因此它是传递给 encrypt()
的字符串参数中的单个字符。要解决这个问题,只需循环遍历 s
列表中所有可能的索引,这些索引恰好与原始字符串的长度相同:
def encrypt(s):
lenStr=len(s)
s=list(s) # convert the string to a list
for i in range(lenStr):
s[i]=ord(s[i])
s[i]=chr(s[i])
这将允许您的代码运行而不会出现该错误。根据您对要实现的加密算法的描述,需要注意的一件事是产生超出 0-255 范围的非法 8 位字符值。您可以通过简单地将 mod 运算符 %
应用于中间结果来避免该问题,以使值保持在正确的范围内。这就是我的意思:
def encrypt(s):
lenStr = len(s)
s = list(s) # convert the string to a list
for i in range(lenStr):
s[i] = chr((ord(s[i]) + lenStr) % 256)
return ''.join(s) # convert list back into a string
同样,解密字符串时您必须执行相同的操作:
def decrypt(s):
lenStr = len(s)
s = list(s) # convert the string to a list
for i in range(lenStr):
s[i] = chr((ord(s[i]) - lenStr) % 256)
return ''.join(s) # convert list back into a string
enc = encrypt('Gnomorian')
print('encrypted:', enc)
dec = decrypt(enc)
print('decrypted:', dec)
输出:
encrypted: Pwxvx{rjw
decrypted: Gnomorian
另请注意,并非所有 ord()
值在 0-255 范围内的字符都是可打印的,因此如果有要求,您可能需要进一步限制加密转换(即加密版本可打印)。
关于python列表索引必须是整数而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17749090/