2011-04-04 55 views
0

我有一個要求「對字符串的UTF-8字節執行SHA1哈希」。我不確定如何獲取UTF-8字節。這裏是什麼,我應該得到一個例子:從Ruby中的字符串獲取UTF-8字節

original = "http://www.provider.com/article?query=mysearch&abcd&1300459467&our secret key" 
#Perform the sha1 hashing on the UTF-8 bytes of this string, to get ... 
expected_hashed = "99802fec87b6ef1d45bd07f3053d13 6cfcfbdf0b" 
#... which is a 160 byte fingerprint. 
#You need to then take the 20 byte representation of this string (make sure you're 
#not just taking the hex string), and base 64 encode that. 
expected_encoded = "mYAv7Ie27x1FvQfzBT0TbPz73ws=" 

它從originalexpected_hashed多數民衆贊成讓我有問題越來越:我不知道如何讓UTF-8字節出來。我正在做SHA1散列,如Digest::SHA1.digest(unhashed_string),我也不是100%確定在這種情況下也是合適的。 :/我也不確定「這個字符串的20字節表示」是什麼。

+0

實際上找出了utf-8/hashing部分:如果我做了'Digest :: SHA1.hexdigest(unhashed_string)',它給了expected_hashed值。儘管如此,我仍然不知道20字節的表示是什麼意思。 – 2011-04-04 12:16:30

+0

什麼版本的Ruby? – 2011-04-04 12:16:36

+0

'紅寶石1.8.6(2007-09-23 patchlevel 110)[x86_64-linux]'(這是一箇舊服務器) – 2011-04-04 12:46:24

回答

4
require 'digest' 
require 'base64' 
Base64.encode64(Digest::SHA1.digest(original)[0,20]) 
# => "mYAv7Ie27x1FvQfzBT0TbPz73ws=\n" 
+0

完美!感謝Mladen。 – 2011-04-04 13:58:58

+0

或者你可以這樣做: Digest :: SHA1.base64digest original – Amala 2013-02-05 18:35:09