Rup*_*cio 3 python string recursion crypt des
预期结果:
该程序采用哈希密码作为输入; 这被传递给decrypt函数.该函数迭代每个混合大小写的n字母组合,对每个这样的字符串进行散列.如果找到与输入匹配的内容,则会打印出未散列的密码; 否则,它会退出.
实际结果:
函数仅针对当前迭代中的最后一个字母迭代每个混合大小写字母.
问题描述:
我正在尝试用Python实现一个简单的暴力DES加密密码破解程序.我使用了很多for循环实现了4个字符的密码实现,但现在我想使用递归来重构一段长度.如何迭代每个字符组合,从1-char组合到4个字符的字符串组合?
我想用这一行:
password[i] = string.ascii_letters[j]
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
TypeError: 'str' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
代码段:
def decrypt(encryptedText):
# reference global variable
global password
# check curr password guess length
pwdlen = len(password)
if pwdlen >= 4:
print("Password is longer than 4 characters, exiting...")
exit(2)
# debug lines
print("password is {}".format(password))
print("length: {}".format(pwdlen))
time.sleep(2)
# first two characters is salt
salt = encryptedText[:2]
# Check hashes for every combination of strings and compare them
# starts with last char
for i in range(pwdlen, 0, -1):
for j in range(0, len(string.ascii_letters)):
password = string.ascii_letters[:pwdlen] + string.ascii_letters[j]
hashed = crypt.crypt(password, salt)
# debug line
print(password)
# if found - print password and exit
if hashed == encryptedText:
print(password)
exit(0)
# this makes recursion go through +1 char combinations on every iteration
password = (pwdlen + 1) * 'a'
return decrypt(encryptedText)
Run Code Online (Sandbox Code Playgroud)
字符串是不可变的.您不能为字符串的一部分分配新值.相反,您必须构建一个新值并将其分配给原始变量.例如:
# password[i] = string.ascii_letters[j]
password = password[:i] + string.ascii_letters[j] + password[i+1:]
Run Code Online (Sandbox Code Playgroud)
其次,通过使用itertools包生成所需的所有排列,您可以做得更好.例如,生成的产物asci_letters只要你想了很多次,通过步骤加入这些字母序列.