Cryptographic Hash Functions (digest)
Though it might not be something we do every day, having easy access to the common cryptographic hash functions can be handy for all sorts of things. The digest standard library provides several options, including MD5, SHA1, and SHA2. We’ll cover three simple use cases here: calculating the checksum of a file, uniquely hashing files based on their content, and encrypted password storage.
I won’t get into the details about the differences between various hashing algorithms or their limitations. Though they all have a potential risk for what is known as a collision, where two distinct content keys are hashed to the same value, this is rare enough to not need to worry about in most practical scenarios. Of course, if you’re new to encryption in general, you will want to read up on these techniques elsewhere before attempting to use them for anything nontrivial. Assuming that you accept this responsibility, we can move on to see how these hashing functions can be used in your Ruby applications.
We’ll start with checksums, because these are pretty easy to find in the wild. If you’ve downloaded open source software before, you’ve probably seen MD5 or SHA256 hashes before. I’ll be honest: most of the time I just ignore these, but they do come in handy when you want to verify that an automated download completed correctly. They’re also useful if you have a tendency toward paranoia and want to be sure that the file you are receiving is really what you think ...
Get Ruby Best Practices now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.