aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/test/message_encryptor_test.rb
diff options
context:
space:
mode:
authorMichael Koziarski <michael@koziarski.com>2008-11-25 20:27:54 +0100
committerMichael Koziarski <michael@koziarski.com>2008-11-25 20:51:30 +0100
commit07abc5efe1bc71902b0c517ef97dcb36564f2336 (patch)
treef7874f9b0a4d01e63245a637d79983f4cefbf058 /activesupport/test/message_encryptor_test.rb
parente126e1aac07d353e10fe9871fc3fc3f040cc8911 (diff)
downloadrails-07abc5efe1bc71902b0c517ef97dcb36564f2336.tar.gz
rails-07abc5efe1bc71902b0c517ef97dcb36564f2336.tar.bz2
rails-07abc5efe1bc71902b0c517ef97dcb36564f2336.zip
Add a MessageEncryptor, just like MessageVerifier but using symmetric key encryption.
The use of encryption prevents people from seeing any potentially secret values you've used. It also supports and encrypt_and_sign model to prevent people from tampering with the bits and creating random junk that gets fed to A motivated coder could use this to add an :encrypt=>true option to the cookie store.
Diffstat (limited to 'activesupport/test/message_encryptor_test.rb')
-rw-r--r--activesupport/test/message_encryptor_test.rb46
1 files changed, 46 insertions, 0 deletions
diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb
new file mode 100644
index 0000000000..c0b4a4658c
--- /dev/null
+++ b/activesupport/test/message_encryptor_test.rb
@@ -0,0 +1,46 @@
+require 'abstract_unit'
+
+class MessageEncryptorTest < Test::Unit::TestCase
+ def setup
+ @encryptor = ActiveSupport::MessageEncryptor.new(ActiveSupport::SecureRandom.hex(64))
+ @data = {:some=>"data", :now=>Time.now}
+ end
+
+ def test_simple_round_tripping
+ message = @encryptor.encrypt(@data)
+ assert_equal @data, @encryptor.decrypt(message)
+ end
+
+ def test_encrypting_twice_yields_differing_cipher_text
+ first_messqage = @encryptor.encrypt(@data)
+ second_message = @encryptor.encrypt(@data)
+ assert_not_equal first_messqage, second_message
+ end
+
+ def test_messing_with_either_value_causes_failure
+ text, iv = @encryptor.encrypt(@data).split("--")
+ assert_not_decrypted([iv, text] * "--")
+ assert_not_decrypted([text, munge(iv)] * "--")
+ assert_not_decrypted([munge(text), iv] * "--")
+ assert_not_decrypted([munge(text), munge(iv)] * "--")
+ end
+
+ def test_signed_round_tripping
+ message = @encryptor.encrypt_and_sign(@data)
+ assert_equal @data, @encryptor.decrypt_and_verify(message)
+ end
+
+
+ private
+ def assert_not_decrypted(value)
+ assert_raises(ActiveSupport::MessageEncryptor::InvalidMessage) do
+ @encryptor.decrypt(value)
+ end
+ end
+
+ def munge(base64_string)
+ bits = ActiveSupport::Base64.decode64(base64_string)
+ bits.reverse!
+ ActiveSupport::Base64.encode64s(bits)
+ end
+end