Wednesday, January 30, 2008

Encryption with Digest#SHA

There are several levels of encryption you can use in Digest#SHA.

  1. Digest::SHA1.hexdigest() - produces a 40 characters of hexadecimal digits.
  2. Digest::SHA256.hexdigest() - produces a 64 characters of hexadecimal digits
  3. Digest::SHA384.hexdigest() - produces a 96 characters of hexadecimal digits
  4. Digest::SHA512.hexdigest() - produces a 128 characters of hexadecimal digits

You can check it by trying the following.

Note: To execute the commands, press Enter after typing.

  1. Open your console.
  2. Change the directory to any of your existing rails application.
  3. Type ruby script/console.
  4. Type a = Digest::SHA1.hexdigest(“test”).
  5. Type a.length. It will display the length of the strings in the variable a.
  6. Repeat step 4 but replacing SHA1 with SHA256, SHA384, or SHA 512.

Depending on your required level of security you can choose among the different SHA levels. If you require the highest level of encryption then you can use SHA512.

Most of its use include encrypting passwords before saving it to the database. You can also use it to encrypt files.

Peace!

2 comments:

wgoulet@gmail.com said...

Hi,

Please note that SHA is a hashing function, not an encryption function. SHA (Secure Hash Algorithm) is designed to create a message digest of the input data. Note that hash functions are designed to be one-way functions in that you cannot retrieve your original data from the output of SHA.

You are correct in that hash functions can be used to store passwords because the OS can execute the hash function on user input and compare it to the hashed password value on disk (this is more secure than storing the password directly or even storing the password encrypted).

More typical use cases for SHA is to produce digital signatures and to produce checksums to show that the contents of a file have not been modified since the hash algorithm was executed.

I have a post on my blog at http://blog.securism.com that talks about hash algorithms in much more detail.

Thanks,
Walter

Eric said...

Cool post. Thanks for sharing! Appreciate your comment too Walter.