2017-06-04 42 views
-1

下面的代碼是一個更大的項目的一部分:創建取決於情況的字典(hashlib)

# Todo: automatically generate dict based 
# on hashlib.algorithms_available 
algorithms = {"md5":hashlib.md5, 
       "sha1":hashlib.sha1, 
       "sha224":hashlib.sha224, 
       "sha256":hashlib.sha256, 
       "sha384":hashlib.sha384, 
       "sha512":hashlib.sha512, 
       "sha3_224":hashlib.sha3_224, 
       "sha3_256":hashlib.sha3_256, 
       "sha3_384":hashlib.sha3_384, 
       "sha3_512":hashlib.sha3_512, 
      } 
self.algo, algorithms = algorithms[self.algo], None 

我想使用hashlib的algorithms_availablehashlib.algorithms_available)來創建一個自定義詞典,取決於系統。 key:value對應該像《algorithm name》: hashlib.《algorithm》,但我無法弄清楚。

回答

1

您可以使用hashlib.new獲得算法對象,並創建一個字典,迭代hashlib.algorithms_available

事情是這樣的 -

In : algorithms = {algo:hashlib.new(algo) for algo in hashlib.algorithms_available} 

In : algorithms 
Out: 
{'DSA': <DSA HASH object @ 0x103e824b0>, 
'DSA-SHA': <DSA-SHA HASH object @ 0x103e8ac70>, 
'MD4': <MD4 HASH object @ 0x102e55470>, 
'MD5': <MD5 HASH object @ 0x103e9ddf0>, 
'MDC2': <MDC2 HASH object @ 0x103eeebb0>, 
'RIPEMD160': <RIPEMD160 HASH object @ 0x104012ef0>, 
'SHA': <SHA HASH object @ 0x103c99af0>, 
'SHA1': <SHA1 HASH object @ 0x103ef32f0>, 
'SHA224': <SHA224 HASH object @ 0x1040123b0>, 
'SHA256': <SHA256 HASH object @ 0x103e9d6f0>, 
'SHA384': <SHA384 HASH object @ 0x103ef02b0>, 
'SHA512': <SHA512 HASH object @ 0x103e9d2b0>, 
'dsaEncryption': <dsaEncryption HASH object @ 0x1040120f0>, 
'dsaWithSHA': <dsaWithSHA HASH object @ 0x103e82a30>, 
'ecdsa-with-SHA1': <ecdsa-with-SHA1 HASH object @ 0x103e9d670>, 
'md4': <md4 HASH object @ 0x102de49f0>, 
'md5': <md5 HASH object @ 0x103e8a570>, 
'mdc2': <mdc2 HASH object @ 0x103ef0db0>, 
'ripemd160': <ripemd160 HASH object @ 0x103ef09b0>, 
'sha': <sha HASH object @ 0x102dfb4b0>, 
'sha1': <sha1 HASH object @ 0x103b532b0>, 
'sha224': <sha224 HASH object @ 0x103e9d7b0>, 
'sha256': <sha256 HASH object @ 0x103eee770>, 
'sha384': <sha384 HASH object @ 0x103ef7bf0>, 
'sha512': <sha512 HASH object @ 0x103e9d6b0>}