开发者

Calculating MD5 of UTF-8 encoded string

Does anyone know how to reproduce this C# algorithm in Ruby?

HashAlgorithm algorithm = MD5.Create();
Encoding encoding = new UTF8Encoding();
var sb = new StringBuilder();
foreach (var element in algorithm.ComputeHash(encoding.GetByt开发者_开发知识库es(password)))
{
    sb.Append(element.ToString("X2"));
}
return sb.ToString();

It calculates the MD5 hash of the password after converting it to UTF-8. The hash is represented as a sequence of 32 hexadecimal digits, e.g., "E4D909C290D0FB1CA068FFADDF22CBD0".

Examples:

    "übergeek""1049165D5C22F27B9545F6B3A0DB07E0"

    "Γεια σου""9B2C16CACFE1803F137374A7E96F083F"


Maybe all you need is Digest::MD5 which will produce hexdigests of any string you give it. While Ruby 1.8 is somewhat subtle in its distinction between ISO-Latin1 and UTF-8 character sets, Ruby 1.9 provides much more control here, including conversion. If the string is supplied as UTF8, though, Ruby 1.8 generally leaves it alone, treating it as a simple byte stream.

require 'digest/md5'

def encode_password(password)
  Digest::MD5.hexdigest(password).upcase
end

# Example:
puts encode_password('foo bar')
# => "327B6F07435811239BC47E1544353273"


You'd need something like this

require 'digest/md5'
Digest::MD5.hexdigest(password.encode("UTF-8"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜