create a sha1 hash from a string in ruby

To create a SHA1 hash from a string in Ruby, you can use the OpenSSL library.

main.rb
require 'openssl'

string = "Hello, World!"

sha1_hash = OpenSSL::Digest::SHA1.hexdigest(string)

puts "SHA1 hash of '#{string}': #{sha1_hash}"
144 chars
8 lines

Output:

main.rb
SHA1 hash of 'Hello, World!': 0a4d55a8d778e5022fab701977c5d840bbc486d0
71 chars
2 lines

Here, we require the openssl library and define a string variable containing the text we want to hash.

Next, we use the OpenSSL::Digest::SHA1 class to create a SHA1 hash object. We then pass our string variable into the hexdigest method of the SHA1 hash object to generate the SHA1 hash in string format.

Finally, we print the SHA1 hash using puts.

gistlibby LogSnag