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