I want to create a 32 bit string that I can use as encryption key. This string/key should be derived from a plain text string, e.g.:
'I am a string'
My approach would first be to hash it:
hashed_string = Digest::SHA1.hexdigest('I am a string') # => 'bd82fb0e81ee9f15f5929e0564093bc9f8015f1d'
And then to use just the first 32 characters:
hashed_string[0..31] # => 'bd82fb0e81ee9f15f5929e0564093bc9'
However, I feel there must be a better approach, and I'm not sure if I risk the possibility of 2 input strings yielding similar keys.
What would be a better approach? I have seen this post that touches on truncation, but can't find an answer that appeals to me there.
If you want a string with 32 bits out of your (weak) password :
Digest::SHA1.digest('I am a string').unpack('B32').first
#=> "10111101100000101111101100001110"
The same amount of information can also be displayed with 8 hexadecimal digits :
Digest::SHA1.hexdigest('I am a string')[0,8]
#=> "bd82fb0e"
or 4 ascii chars :
Digest::SHA1.digest('I am a string')[0,4]
#=> "\xBD\x82\xFB\x0E"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With