UTF-8 encoded string MD5 calculation

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.GetBytes(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, for example, "E4D909C290D0FB1CA068FFADDF22CBD0".

Examples:

  "übergeek""1049165D5C22F27B9545F6B3A0DB07E0"
  "Γεια σου""9B2C16CACFE1803F137374A7E96F083F"

+3
source share
2 answers

, , , Digest:: MD5, hexdigests , . Ruby 1.8 ISO-Latin1 UTF-8, Ruby 1.9 , . UTF8, Ruby 1.8 , .

require 'digest/md5'

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

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

-

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

Source: https://habr.com/ru/post/1728318/


All Articles