1

Pythonオブジェクトをmd5ハッシュする関数を作成しようとしています。そして、私はpython2とpython3で同じmd5値を返したいと思っています。

python3 では pickle.dumps を知っています。バイトを返し、python2 では str を返します。ご覧のとおり、次のコードで同じ文字列が得られます。

print( [      pickle.dumps( obj, protocol = 2 )   ] ) # in python2
print( [ str( pickle.dumps( obj, protocol = 2 ) ) ] ) # in python3

どちらも私に与えます:

['\x80\x02]q\x00(U\x011q\x01K\x02U\x013q\x02K\x04e.']

しかし問題は、python3 では次のことです。

hashlib.md5.update( some_string )

エンコードする必要があります。文字列を python3 でエンコードすると、python2 と同じ md5 値が得られません。誰が解決策を教えてくれますか? 君たちありがとう。

ここに私のコードがあります:

from __future__ import print_function
import hashlib
import pickle
import sys

is_py2 = (sys.version_info[0] == 2)

obj = ['1',2,'3',4]
m = hashlib.md5()

if is_py2:                                                    # if it's python2
    print(    [      pickle.dumps( obj, protocol = 2 ) ] )
    m.update(        pickle.dumps( obj, protocol = 2 )   )
else:                                                         # if it's python3
    print(    [ str( pickle.dumps( obj, protocol = 2 ) ) ] )
    m.update(        pickle.dumps( obj, protocol = 2 ).encode( "utf-8" ) ) # I wish I could don not encode

print( m.hexdigest() )
4

2 に答える 2

0

2x および 3x エンコーディングを実行するための 1 つのライナーがあり、任意のエンコーディングに対して実行できます。

>>> hashlib.new(algorithm, repr(object).encode()).hexdigest()

変数名の完全なコンテキストについては、https ://github.com/uqfoundation/klepto/blob/master/klepto/crypto.py#L26 を参照してください。エンコーディング、シリアライゼーション、など。すべて Python 2.x および 3.x で動作します。

Python 2.x と 3.x が同じハッシュを返すようにしたいようです。うーん...うまくいかないと思います。2.x で 3.xと同じエンコーディングを返す可能性がある場合、または(プロトコル 2) などで最初md5にヒットする必要があるかもしれません。reprpickle

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import klepto
>>> klepto.crypto.hash(klepto.crypto.pickle(object), algorithm='md5')
'ee16782749cb00e4b66922df545877f0'

そのため、 pickle andmd5は機能していないようであり、一部のオブジェクトが 2.x と 3.x の間で変更されているため、通常は機能しないはずです (たとえば、objectは でしたが、typeは になりましたclass)。それはまたrepr、一般的にエンコーダーとしても機能しないことを意味します。

Python 3.3.5 (default, Mar 10 2014, 21:37:38) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import klepto
>>> klepto.crypto.hash(klepto.crypto.pickle(object), algorithm='md5')
'35eb4c374cafe09c8ac01661701b6b6e'

多分kleptoあなたのために働く の他のエンコーダーの 1 つがあるでしょう。

于 2014-10-12T15:58:12.997 に答える