我试图写一个函数,它会递归地散列一次键n次,在sha224和sha256之间交替。每次迭代都是hash_256(hash_224) - 密钥的hash224的hash256 - 这样它就会产生n *(hash_256(hash_224))。但是,我是编码的新手,无法弄清楚如何使用这些参数编写递归函数。
import hashlib
def shasum(key, n):
key = str(key).encode('utf-8')
hash_a = hashlib.sha224(key).hexdigest().encode('utf-8'))
hash_b = hashlib.sha256(hash_a).hexdigest()
if n == 0 or 1:
return hash_b #one iteration of 256(224)
else:
return n-1
return hash_b #stuck here
编辑:现在它的行为就像一个数字生成器。怎么了?
import hashlib
n = 0
def sha480(seed):
hashed_224 = str(hashlib.sha224(seed)).encode('utf-8')
hashed_256 = hashlib.sha256(hashed_224).hexdigest()
hashed_480 = str(hashed_256)
print("hash: " + hashed_480)
def repeater(key, n):
if n == 0:
return key
seed = str(key).encode('utf-8')
while n > 0:
return sha480(repeater(seed, n-1))
repeater('what', 2)
答案 0 :(得分:0)
根本没有递归调用。您可以将其更改为:
def hash_a(key):
return hashlib.sha224(key).hexdigest().encode('utf-8')
def hash_b(key):
return hashlib.sha256(key).hexdigest()
def shasum(key, n):
if n == 0: # base case: 0 iterations -> return key itself
return key
key = str(key).encode('utf-8')
return hash_b(hash_a(shasum(key, n - 1))) # recursve call
附注:n == 0 or 1
相当于(n == 0) or 1
,它始终为真。对于该模式,请使用n == 0 or n == 1
或更短n in (0, 1)
答案 1 :(得分:0)
您的代码几乎是正确的。只是一些小问题修复如下
import hashlib
def shasum(key, n):
print ("n: " + str(n))
key = str(key).encode('utf-8')
hash_a = hashlib.sha224(key).hexdigest().encode('utf-8')
print ("hash_a: " + str(hash_a))
hash_b = hashlib.sha256(hash_a).hexdigest()
print ("hash_b: " + str(hash_b))
if n == 0:
return hash_b #one iteration of 256(224)
else:
return shasum(hash_b, n-1)