Skip to content
Browse files

Added UserSafe stuff for encryption strategy

  • Loading branch information...
1 parent 156f8a3 commit 0c7ece38f8bb07bf7ca6f47b1c772240b5fcf625 @LupusDei committed Apr 30, 2012
Showing with 90 additions and 0 deletions.
  1. +57 −0 lib/user_safe.rb
  2. +33 −0 spec/lib/user_safe_spec.rb
View
57 lib/user_safe.rb
@@ -0,0 +1,57 @@
+require 'openssl'
+
+module UserSafe
+
+ def self.generate_pair(password)
+ private_key = OpenSSL::PKey::RSA.generate(2048).to_s
+ pair = OpenSSL::PKey::RSA.new(private_key)
+
+ public_key = pair.public_key.to_s
+
+ encrypted_private_key = encrypt_private_key(public_key, private_key, password)
+ [public_key, encrypted_private_key]
+ end
+
+ def self.encrypt(data, public_key)
+ encryptifier = OpenSSL::PKey::RSA.new(public_key)
+ encryptifier.public_encrypt(data)
+ end
+
+ def self.decrypt(encrypted_data, public_key, encrypted_private_key, password)
+ private_key = decrypt_private_key(public_key, encrypted_private_key, password)
+ decryptifier = OpenSSL::PKey::RSA.new(private_key)
+ decryptifier.private_decrypt(encrypted_data)
+ end
+
+
+ private
+
+ def self.encrypt_private_key(public_key, private_key, password)
+ key = to_256_key(password)
+ cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
+ cipher.encrypt
+ cipher.key = key
+ cipher.iv = public_key
+
+ cipher.update(private_key) + cipher.final
+ end
+
+ def self.decrypt_private_key(public_key, encrypted_private_key, password)
+ key = to_256_key(password)
+ cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
+ cipher.decrypt
+ cipher.key = key
+ cipher.iv = public_key
+
+ cipher.update(encrypted_private_key) + cipher.final
+ end
+
+ def self.to_256_key(short_key)
+ key = short_key
+ while key.size < 256
+ key += short_key
+ end
+ key[0..256]
+ end
+
+end
View
33 spec/lib/user_safe_spec.rb
@@ -0,0 +1,33 @@
+require 'spec_helper'
+require File.expand_path("../../lib/user_safe.rb", File.dirname(__FILE__))
+describe UserSafe do
+
+ it "can generate a public key and encrypted private key" do
+ pair = UserSafe.generate_pair("password")
+ pair.size.should == 2
+ end
+
+ it "can encrypt data" do
+ public_key, _ = UserSafe.generate_pair("password")
+ result = UserSafe.encrypt("some data", public_key)
+ result.should_not == "some data"
+ end
+
+ def rand_word(size = 10)
+ word = ""
+ size.times { word << ('A'..'z').to_a.sample }
+ word
+ end
+
+ it "can decrypt the encrypted data" do
+ password = rand_word(20)
+ data = rand_word(243)
+ public_key, encrypted_private_key = UserSafe.generate_pair(password)
+
+ encrypted_data = UserSafe.encrypt(data, public_key)
+ puts "size: #{encrypted_data.size}"
+
+ UserSafe.decrypt(encrypted_data, public_key, encrypted_private_key, password).should == data
+ end
+
+end

0 comments on commit 0c7ece3

Please sign in to comment.
Something went wrong with that request. Please try again.