views:

183

answers:

3

In ruby, I encrypt a string using "crypt" method, for example:

str = "123"

strencrypt = str.crypt("aa")

I want to decrypt from strencrypt and obtain the original string. How can I achieve that? I have tried to use crypt method again:

str_ori = strencrypt.crypt("aa")

But it can not return the "123".

Anyone can help me?

+2  A: 

You can't. str.crypt is a one-way hash function.

Tadmas
+2  A: 

str.crypt is a one-way cryptographic hash. You can not decrypt the string.

See this question for explanations of one-way cryptographic hashes in general.

Karl Voigtland
+5  A: 

you can't - it's one-way encryption. if you're wondering why that's useful, one standard use case is to do password validation:

pass = "helloworld"
$salt = "qw"
$cpass = pass.crypt($salt)

def validate_pass(guess)
  guess.crypt($salt) == $cpass
end

while true
  puts "enter password"
  pass = gets
  if validate_pass(pass)
    print "validated"
    break
  end
end

note that the validate_pass function neither has nor needs access to the original plaintext password.

Martin DeMello