2.26. Encrypting StringsThere are times when we don't want strings to be immediately legible. For example, passwords should not be stored in plaintext, no matter how tight the file permissions are. The standard method crypt uses the standard function of the same name to DES-encrypt a string. It takes a "salt" value as a parameter (similar to the seed value for a random number generator). On non-UNIX platforms, this parameter may be different. A trivial application for this follows, where we ask for a password that Tolkien fans should know: coded = "hfCghHIE5LAM." puts "Speak, friend, and enter!" print "Password: " password = gets.chop if password.crypt("hf") == coded puts "Welcome!" else puts "What are you, an orc?" end It is worth noting that you should never rely on encryption of this nature for a server-side web application because a password entered on a web form is still transmitted over the Internet in plaintext. In a case like this, the easiest security measure is the Secure Sockets Layer (SSL). Of course, you could still use encryption on the server side, but for a different reasonto protect the password as it is stored rather than during transmission. |