2017-05-11 46 views
0

我想用Python3使用事件API。在當前狀態下,登錄功能使用不推薦使用的md5庫。因此,我想將此函數轉換爲Python 3兼容。我與面臨困境的線是:Python3:用hashlib替換md5

response = md5.new(nonce + ':'+ md5.new(password).hexdigest()).hexdigest() 

我嘗試將其轉換爲

mpwd = hashlib.md5(password.encode()) 
    apwd = mpwd.hexdigest() 
    s = nonce+":"+apwd 
    mall = hashlib.md5(s.encode()) 
    response = mall.hexdigest() 

不幸的是,API返回的說,無論是登錄或密碼不正確的錯誤。但是,我檢查了兩個都沒問題。那麼請你告訴我我的代碼有什麼問題嗎?

回答

1

這裏的東西,你真的應該張貼之前曾嘗試:

的Python 2.7:

>>> import md5 
>>> password = 'fred' 
>>> nonce = '12345' 
>>> md5.new(nonce + ':'+ md5.new(password).hexdigest()).hexdigest() 
'496a1ca20abf5b0b12ab7f9891d04201' 

的Python 2.7和Python 3.6:

>>> import hashlib 
>>> password = 'fred' 
>>> nonce = '12345' 
>>> mpwd = hashlib.md5(password.encode()) 
>>> apwd = mpwd.hexdigest() 
>>> s = nonce+":"+apwd 
>>> mall = hashlib.md5(s.encode()) 
>>> mall.hexdigest() 
'496a1ca20abf5b0b12ab7f9891d04201' 

正如你可以看到,這兩個版本產生相同的md5散列。所以問題不在於你的代碼。這可能與你在用這一位代碼之後用response做什麼有關。或者,也許API是正確的,登錄確實是錯誤的。

-1

您的代碼是正確的。 如果您在md5之前添加hashlib並在導入md5之前加上「#」,問題就會解決。

進口hashlib (從文件中刪除「進口MD5」)

def login(self, user, password): 
    "Login to the Eventful API as USER with PASSWORD." 
    nonce = self.call('/users/login')['nonce'] 
    response = hashlib.md5.new(nonce + ':'+ hashlib.md5.new(password).hexdigest()).hexdigest() 

    login = self.call('/users/login', user=user, nonce=nonce, 
         response=response) 
    self.user_key = login['user_key'] 
    self.user = user 
    return user 
+0

,如果你在你的答案重寫代碼它的更好,將與其中的變化 – Michael