I'm not a cryptographer, but .... One way you could do this,
depending on your app requirements, is to follow an asymmetric
encryption strategy using pub/priv keys, something like:
### gen pub/priv keys to use:
$ cd ./private
$ openssl genrsa -out asym_priv.key 2048
...
$ openssl rsa -in asym_priv.key -out asym_pub.key -pubout
...
$ chmod 400 asym_priv.key
$ chmod 444 asym_pub.key
$ cd ..
### cat ./app/model/cryptor.rb
require 'digest/sha2'
require 'openssl'
class Cryptor
include Singleton
ASYM_PUB_KEY = OpenSSL::PKey::RSA.new(IO.read("#{RAILS_ROOT}/private/
asym_pub.key"))
ASYM_PRIV_KEY = OpenSSL::PKey::RSA.new(IO.read("#{RAILS_ROOT}/
private/asym_priv.key"))
...
def Cryptor.asym_encrypt(str)
return Base64.encode64(ASYM_PUB_KEY.public_encrypt(str))
end
def Cryptor.asym_decrypt(str)
return ASYM_PRIV_KEY.private_decrypt(Base64.decode64(str))
end
...
end
### and then test it out:
$ ./script/console
...
>> enc_str = Cryptor.asym_encrypt('testing 1 2 3')
=> "i4d/uc6w1NGCUQLspM7CMsvNMd
+4dFrx3yb0QhM4N3di6Yha8jeW5Ftx4ZA2\nnPn4AzhZPzCrQdds/ERP0Lb9X/
dzJaJt5Tyig12hl4EqlILTnSj9SlPatIr9\n2m9D0K416BRuCJaWOp0lhXIe1XCZisjKKhLhR1T3nH
+NjQnNx4HBFhrFOnSz
\nuWpNfQf8sYxhLiSiKwTy3WUPmSRHPgu8h5mIgtxjU12spf0NvbZEDzwP+/br
\nWMJNQ6rGSNP6smd3YahoQzYjNFn3v+YCjG497eIdHNOBN6LAnW+HoB1TD5qm
\ngJzuOIk1eownT9kfjiykR+lNmw1kNX3bzDqdBvsB8g==\n"
>> dec_str = Cryptor.asym_decrypt(enc_str)
=> "testing 1 2 3"
Using Base64 isn't necessary if your db tbls can handle binary, but it
can be a help when you're testing/debugging. Also, the size of your
priv key in bits will definitely effect performance of encrypt/decrypt
process, so you'll want to choose according to needs, balancing
performance vs encrypt-strength.
And if such an asym strategy is just too slow for your needs, then you
could pursue a symmetric strategy instead, which would be much faster
in terms of performance, but more complex to implement (likely having
to persist the initialization vector -- iv -- val used when sym
encrypting some val for later use when sym decrypting that val again).
Jeff
On Mar 10, 8:15 am, Jeff Pritchard <[email protected]>
wrote:
> MaD wrote:
> > depends on what you are looking for. if want to have a one-way
> > function (for passwords and such) just try it like this:
>
> > encrypted_item = Digest::SHA256.hexdigest( string_to_encrypt )
>
> > you could also use SHA1, SHA384, SHA512 depending on your need of
> > security.
>
> Thanks, but I need to decrypt it also. It is "for your eyes only" user
> data.
>
> thanks,
> jp
> --
> Posted viahttp://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---