如何使用python获取字符串的MD5总和?

时间:2011-03-14 10:38:56

标签: python md5 flickr

Flickr API docs中,您需要找到字符串的MD5总和以生成[api_sig]值。

如何从字符串生成MD5总和?

Flickr的例子:

字符串:000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite

MD5总和:a02506b31c1cd46c2e0b6380fb94eb3d

7 个答案:

答案 0 :(得分:475)

您可以执行以下操作:

Python 2.x

import hashlib
print hashlib.md5("whatever your string is").hexdigest()

Python 3.x

import hashlib
print(hashlib.md5("whatever your string is".encode('utf-8')).hexdigest())

但是在这种情况下,您可能最好使用这个有用的Python模块与Flickr API进行交互:

...将为您处理身份验证。

hashlib

的官方文件

答案 1 :(得分:225)

对于Python 2.x,使用python的hashlib

import hashlib
m = hashlib.md5()
m.update("000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite")
print m.hexdigest()

输出:a02506b31c1cd46c2e0b6380fb94eb3d

答案 2 :(得分:9)

您是否尝试在hashlib中使用MD5实施?请注意,散列算法通常作用于二进制数据而不是 text 数据,因此您可能需要注意在散列之前使用哪种字符编码将文本转换为二进制数据

散列的结果也是二进制数据 - 看起来Flickr的示例已经使用十六进制编码转换为文本。使用hashlib中的hexdigest函数来获取此功能。

答案 3 :(得分:7)

在 Python 3 中使用 hashlib.md5。

import hashlib

source = '000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite'.encode()
md5 = hashlib.md5(source).hexdigest() # returns a str
print(md5) # a02506b31c1cd46c2e0b6380fb94eb3d

如果您需要字节类型输出,请使用 digest() 而不是 hexdigest()

答案 4 :(得分:2)

foreach($user->products()->get(['price','amount']) as $product){
        $order->products()->attach($product, array('history_price'=> $product->price, 'amount'=>$product->amount,'order_id'=>$order->id, 'product_id'=>$product->id));
}
$order->save();

答案 5 :(得分:0)

您可以尝试

>>> from datetime import date
>>> week_from_date(date(2015, 12, 27))
(2016, 1)

答案 6 :(得分:0)

您可以使用b character in front of a string literal

import hashlib
print(hashlib.md5(b"Hello MD5").hexdigest())
print(hashlib.md5("Hello MD5".encode('utf-8')).hexdigest())

出局:

e5dadf6524624f79c3127e247f04b548
e5dadf6524624f79c3127e247f04b548