2011-04-04 5 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=" 

をそれはoriginalから私に問題を与えているexpected_hashedになっています:私は、UTF-8バイトを取得する方法がわからない。ここで私は取得すべきかの例を示します。私はDigest::SHA1.digest(unhashed_string)のようなSHA1のハッシングをしていますが、私はこのインスタンスにも適切であると100%確信していません。 :/私はまた、この文字列の "20バイト表現"が何であるかについても不明です。

+0

実際にはutf-8 /ハッシング部分を見つけました:もし私が 'Digest :: SHA1.hexdigest(unhashed_string)'を実行すると、expected_hashed値が得られます。私はまだこの20バイトの表現が何を意味するのかわかりません。 –

+0

Rubyのどのバージョンですか? –

+0

'ruby 1.8.6(2007-09-23 patchlevel 110)[x86_64-linux]'(これは古いサーバーです) –

答えて

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

Perfect!ありがとうMladen。 –

+0

または次の操作を行うことができます。 Digest :: SHA1.base64digest original – Amala

関連する問題