【问题标题】:Get UTF-8 bytes from a string in Ruby从 Ruby 中的字符串中获取 UTF-8 字节
【发布时间】:2011-07-29 03:17:42
【问题描述】:

我需要“对字符串的 UTF-8 字节执行 SHA1 散列”。我不确定如何取出 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 字节。我正在像Digest::SHA1.digest(unhashed_string) 一样进行SHA1 散列,我也不是100% 确定这在这种情况下是否合适。 :/ 我也不确定“这个字符串的 20 字节表示”是什么。

【问题讨论】:

  • 实际上找出了 utf-8/hashing 部分:如果我这样做 Digest::SHA1.hexdigest(unhashed_string) 这给了我 expected_hashed 值。不过,我仍然不知道这 20 字节的表示是什么意思。
  • ruby 1.8.6 (2007-09-23 patchlevel 110) [x86_64-linux](旧服务器)

标签: ruby string utf-8 sha1


【解决方案1】:
require 'digest'
require 'base64'
Base64.encode64(Digest::SHA1.digest(original)[0,20])
# => "mYAv7Ie27x1FvQfzBT0TbPz73ws=\n" 

【讨论】:

  • 或者你可以这样做:Digest::SHA1.base64digest original
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2017-09-16
  • 1970-01-01
  • 2015-09-01
相关资源
最近更新 更多