Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Rename namespace from Symmetric to SymmetricEncryption and Symmetric:…

…:Encryption.encrypt to SymmetricEncryption.encrypt
  • Loading branch information...
commit dc8c016160c0c68c339c82aa650a78163bea2e53 1 parent 2c69eac
@reidmorrison authored
Showing with 447 additions and 456 deletions.
  1. +9 −9 lib/symmetric-encryption.rb
  2. +0 −283 lib/symmetric/encryption.rb
  3. +0 −4 lib/symmetric/version.rb
  4. +1 −5 lib/{symmetric → symmetric_encryption}/cipher.rb
  5. +4 −4 lib/{symmetric → symmetric_encryption}/extensions/active_record/base.rb
  6. +8 −8 lib/{symmetric → symmetric_encryption}/extensions/mongoid/fields.rb
  7. +2 −2 lib/{symmetric → symmetric_encryption}/railtie.rb
  8. +5 −5 lib/{symmetric → symmetric_encryption}/railties/symmetric_encryption.rake
  9. +4 −4 ...es/symmetric_encrypted_validator.rb → symmetric_encryption/railties/symmetric_encryption_validator.rb}
  10. +39 −42 lib/{symmetric/encryption_reader.rb → symmetric_encryption/reader.rb}
  11. +280 −0 lib/symmetric_encryption/symmetric_encryption.rb
  12. +4 −0 lib/symmetric_encryption/version.rb
  13. +6 −6 lib/{symmetric/encryption_writer.rb → symmetric_encryption/writer.rb}
  14. +7 −7 test/attr_encrypted_test.rb
  15. +6 −6 test/cipher_test.rb
  16. +0 −52 test/encryption_test.rb
  17. +3 −3 test/field_encrypted_test.rb
  18. +10 −10 test/{encryption_reader_test.rb → reader_test.rb}
  19. +53 −0 test/symmetric_encryption_test.rb
  20. +6 −6 test/{encryption_writer_test.rb → writer_test.rb}
View
18 lib/symmetric-encryption.rb
@@ -1,19 +1,19 @@
-require 'symmetric/version'
-require 'symmetric/cipher'
-require 'symmetric/encryption'
-require 'symmetric/encryption_reader'
-require 'symmetric/encryption_writer'
+require 'symmetric_encryption/version'
+require 'symmetric_encryption/cipher'
+require 'symmetric_encryption/symmetric_encryption'
+require 'symmetric_encryption/reader'
+require 'symmetric_encryption/writer'
require 'zlib'
if defined?(Rails)
- require 'symmetric/railtie'
+ require 'symmetric_encryption/railtie'
end
# attr_encrypted and Encrypted validator
if defined?(ActiveRecord::Base)
- require 'symmetric/extensions/active_record/base'
- require 'symmetric/railties/symmetric_encrypted_validator'
+ require 'symmetric_encryption/extensions/active_record/base'
+ require 'symmetric_encryption/railties/symmetric_encryption_validator'
end
# field encryption for Mongoid
if defined?(Mongoid)
- require 'symmetric/extensions/mongoid/fields'
+ require 'symmetric_encryption/extensions/mongoid/fields'
end
View
283 lib/symmetric/encryption.rb
@@ -1,283 +0,0 @@
-require 'base64'
-require 'openssl'
-require 'zlib'
-require 'yaml'
-
-module Symmetric
-
- # Encrypt using 256 Bit AES CBC symmetric key and initialization vector
- # The symmetric key is protected using the private key below and must
- # be distributed separately from the application
- class Encryption
-
- # Defaults
- @@cipher = nil
- @@secondary_ciphers = []
-
- # Set the Primary Symmetric Cipher to be used
- def self.cipher=(cipher)
- raise "Cipher must be similar to Symmetric::Ciphers" unless cipher.respond_to?(:encrypt) && cipher.respond_to?(:decrypt)
- @@cipher = cipher
- end
-
- # Returns the Primary Symmetric Cipher being used
- # If a version is supplied, then the cipher matching that version will be
- # returned or nil if no match was found
- def self.cipher(version = nil)
- return @@cipher if version.nil? || (@@cipher.version == version)
- secondary_ciphers.find {|c| c.version == version}
- end
-
- # Set the Secondary Symmetric Ciphers Array to be used
- def self.secondary_ciphers=(secondary_ciphers)
- raise "secondary_ciphers must be a collection" unless secondary_ciphers.respond_to? :each
- secondary_ciphers.each do |cipher|
- raise "secondary_ciphers can only consist of Symmetric::Ciphers" unless cipher.respond_to?(:encrypt) && cipher.respond_to?(:decrypt)
- end
- @@secondary_ciphers = secondary_ciphers
- end
-
- # Returns the Primary Symmetric Cipher being used
- def self.secondary_ciphers
- @@secondary_ciphers
- end
-
- # AES Symmetric Decryption of supplied string
- # Returns decrypted string
- # Returns nil if the supplied str is nil
- # Returns "" if it is a string and it is empty
- #
- # Note: If secondary ciphers are supplied in the configuration file the
- # first key will be used to decrypt 'str'. If it fails each cipher in the
- # order supplied will be tried.
- # It is slow to try each cipher in turn, so should be used during migrations
- # only
- #
- # Raises: OpenSSL::Cipher::CipherError when 'str' was not encrypted using
- # the supplied key and iv
- #
- def self.decrypt(str)
- raise "Call Symmetric::Encryption.load! or Symmetric::Encryption.cipher= prior to encrypting or decrypting data" unless @@cipher
- binary = ::Base64.decode64(str) if str
- begin
- @@cipher.decrypt(binary)
- rescue OpenSSL::Cipher::CipherError => exc
- @@secondary_ciphers.each do |cipher|
- begin
- return cipher.decrypt(binary)
- rescue OpenSSL::Cipher::CipherError
- end
- end
- raise exc
- end
- end
-
- # AES Symmetric Encryption of supplied string
- # Returns result as a Base64 encoded string
- # Returns nil if the supplied str is nil
- # Returns "" if it is a string and it is empty
- def self.encrypt(str)
- raise "Call Symmetric::Encryption.load! or Symmetric::Encryption.cipher= prior to encrypting or decrypting data" unless @@cipher
-
- # Encrypt data as a binary string
- result = @@cipher.encrypt(str)
-
- # Base 64 Encoding of binary data
- result = ::Base64.encode64(result) if result
- result
- end
-
- # Invokes decrypt
- # Returns decrypted String
- # Return nil if it fails to decrypt a String
- #
- # Useful for example when decoding passwords encrypted using a key from a
- # different environment. I.e. We cannot decode production passwords
- # in the test or development environments but still need to be able to load
- # YAML config files that contain encrypted development and production passwords
- def self.try_decrypt(str)
- raise "Call Symmetric::Encryption.load! or Symmetric::Encryption.cipher= prior to encrypting or decrypting data" unless @@cipher
- begin
- decrypt(str)
- rescue OpenSSL::Cipher::CipherError
- nil
- end
- end
-
- # Returns [true|false] as to whether the data could be decrypted
- # Parameters:
- # encrypted_data: Encrypted string
- def self.encrypted?(encrypted_data)
- raise "Call Symmetric::Encryption.load! or Symmetric::Encryption.cipher= prior to encrypting or decrypting data" unless @@cipher
-
- # First make sure Base64 encoded data still ends with "\n" since it could be used in a key field somewhere
- return false unless encrypted_data.end_with?("\n")
-
- # For now have to decrypt it fully
- !try_decrypt(encrypted_data).nil?
- end
-
- # Load the Encryption Configuration from a YAML file
- # filename:
- # Name of file to read.
- # Mandatory for non-Rails apps
- # Default: Rails.root/config/symmetric-encryption.yml
- # environment:
- # Which environments config to load. Usually: production, development, etc.
- # Default: Rails.env
- def self.load!(filename=nil, environment=nil)
- config = read_config(filename, environment)
-
- # Check for hard coded key, iv and cipher
- if config[:key]
- @@cipher = Cipher.new(config)
- @@secondary_ciphers = []
- else
- private_rsa_key = config[:private_rsa_key]
- @@cipher, *@@secondary_ciphers = config[:ciphers].collect do |cipher_conf|
- cipher_from_encrypted_files(
- private_rsa_key,
- cipher_conf[:cipher],
- cipher_conf[:key_filename],
- cipher_conf[:iv_filename])
- end
- end
-
- true
- end
-
- # Future: Generate private key in config file generator
- #new_key = OpenSSL::PKey::RSA.generate(2048)
-
- # Generate new random symmetric keys for use with this Encryption library
- #
- # Note: Only the current Encryption key settings are used
- #
- # Creates Symmetric Key .key
- # and initilization vector .iv
- # which is encrypted with the above Public key
- #
- # Warning: Existing files will be overwritten
- def self.generate_symmetric_key_files(filename=nil, environment=nil)
- config = read_config(filename, environment)
- cipher_cfg = config[:ciphers].first
- key_filename = cipher_cfg[:key_filename]
- iv_filename = cipher_cfg[:iv_filename]
- cipher = cipher_cfg[:cipher]
-
- raise "The configuration file must contain a 'private_rsa_key' parameter to generate symmetric keys" unless config[:private_rsa_key]
- rsa_key = OpenSSL::PKey::RSA.new(config[:private_rsa_key])
-
- # Generate a new Symmetric Key pair
- key_pair = Symmetric::Cipher.random_key_pair(cipher || 'aes-256-cbc', !iv_filename.nil?)
-
- # Save symmetric key after encrypting it with the private RSA key, backing up existing files if present
- File.rename(key_filename, "#{key_filename}.#{Time.now.to_i}") if File.exist?(key_filename)
- File.open(key_filename, 'wb') {|file| file.write( rsa_key.public_encrypt(key_pair[:key]) ) }
-
- if iv_filename
- File.rename(iv_filename, "#{iv_filename}.#{Time.now.to_i}") if File.exist?(iv_filename)
- File.open(iv_filename, 'wb') {|file| file.write( rsa_key.public_encrypt(key_pair[:iv]) ) }
- end
- puts("Generated new Symmetric Key for encryption. Please copy #{key_filename} and #{iv_filename} to the other web servers in #{environment}.")
- end
-
- # Generate a 22 character random password
- def self.random_password
- Base64.encode64(OpenSSL::Cipher.new('aes-128-cbc').random_key)[0..-4]
- end
-
- # Binary encrypted data includes this magic header so that we can quickly
- # identify binary data versus base64 encoded data that does not have this header
- unless defined? MAGIC_HEADER
- MAGIC_HEADER = '@EnC'
- MAGIC_HEADER_SIZE = MAGIC_HEADER.size
- MAGIC_HEADER_UNPACK = "A#{MAGIC_HEADER_SIZE}v"
- end
-
- protected
-
- # Returns the Encryption Configuration
- #
- # Read the configuration from the YAML file and return in the latest format
- #
- # filename:
- # Name of file to read.
- # Mandatory for non-Rails apps
- # Default: Rails.root/config/symmetric-encryption.yml
- # environment:
- # Which environments config to load. Usually: production, development, etc.
- def self.read_config(filename=nil, environment=nil)
- config = YAML.load_file(filename || File.join(Rails.root, "config", "symmetric-encryption.yml"))[environment || Rails.env]
-
- # Default cipher
- default_cipher = config['cipher'] || 'aes-256-cbc'
- cfg = {}
-
- # Hard coded symmetric_key? - Dev / Testing use only!
- if symmetric_key = (config['key'] || config['symmetric_key'])
- raise "Symmetric::Encryption Cannot hard code Production encryption keys in #{filename}" if (environment || Rails.env) == 'production'
- cfg[:key] = symmetric_key
- cfg[:iv] = config['iv'] || config['symmetric_iv']
- cfg[:cipher] = default_cipher
-
- elsif ciphers = config['ciphers']
- raise "Missing mandatory config parameter 'private_rsa_key'" unless cfg[:private_rsa_key] = config['private_rsa_key']
-
- cfg[:ciphers] = ciphers.collect do |cipher_cfg|
- key_filename = cipher_cfg['key_filename'] || cipher_cfg['symmetric_key_filename']
- raise "Missing mandatory 'key_filename' for environment:#{environment} in #{filename}" unless key_filename
- iv_filename = cipher_cfg['iv_filename'] || cipher_cfg['symmetric_iv_filename']
- {
- :cipher => cipher_cfg['cipher'] || default_cipher,
- :key_filename => key_filename,
- :iv_filename => iv_filename,
- }
- end
-
- else
- # Migrate old format config
- raise "Missing mandatory config parameter 'private_rsa_key'" unless cfg[:private_rsa_key] = config['private_rsa_key']
- cfg[:ciphers] = [ {
- :cipher => default_cipher,
- :key_filename => config['symmetric_key_filename'],
- :iv_filename => config['symmetric_iv_filename'],
- } ]
- end
-
- cfg
- end
-
- # Returns an instance of Symmetric::Cipher initialized from keys
- # stored in files
- #
- # Raises an Exception on failure
- #
- # Parameters:
- # cipher
- # Encryption cipher for the symmetric encryption key
- # private_key
- # Key used to unlock file containing the actual symmetric key
- # key_filename
- # Name of file containing symmetric key encrypted using the public
- # key matching the supplied private_key
- # iv_filename
- # Optional. Name of file containing symmetric key initialization vector
- # encrypted using the public key matching the supplied private_key
- def self.cipher_from_encrypted_files(private_rsa_key, cipher, key_filename, iv_filename = nil)
- # Load Encrypted Symmetric keys
- encrypted_key = File.read(key_filename)
- encrypted_iv = File.read(iv_filename) if iv_filename
-
- # Decrypt Symmetric Keys
- rsa = OpenSSL::PKey::RSA.new(private_rsa_key)
- iv = rsa.private_decrypt(encrypted_iv) if iv_filename
- Cipher.new(
- :key => rsa.private_decrypt(encrypted_key),
- :iv => iv,
- :cipher => cipher
- )
- end
-
- end
-end
View
4 lib/symmetric/version.rb
@@ -1,4 +0,0 @@
-# encoding: utf-8
-module Symmetric #:nodoc
- VERSION = "0.4.0"
-end
View
6 lib/symmetric/cipher.rb → lib/symmetric_encryption/cipher.rb
@@ -1,8 +1,4 @@
-require 'base64'
-require 'openssl'
-require 'zlib'
-
-module Symmetric
+module SymmetricEncryption
# Hold all information related to encryption keys
# as well as encrypt and decrypt data using those keys
View
8 ...ymmetric/extensions/active_record/base.rb → ...cryption/extensions/active_record/base.rb
@@ -3,7 +3,7 @@ class Base
class << self # Class methods
# Much lighter weight encryption for Rails attributes matching the
- # attr_encrypted interface using Symmetric::Encryption
+ # attr_encrypted interface using SymmetricEncryption
#
# The regular attr_encrypted gem uses Encryptor that adds encryption to
# every Ruby object which is a complete overkill for this simple use-case
@@ -31,7 +31,7 @@ def attr_encrypted(*params)
# If this method is not called, then the encrypted value is never decrypted
def #{attribute}
if @stored_encrypted_#{attribute} != self.encrypted_#{attribute}
- @#{attribute} = ::Symmetric::Encryption.decrypt(self.encrypted_#{attribute})
+ @#{attribute} = ::SymmetricEncryption.decrypt(self.encrypted_#{attribute})
@stored_encrypted_#{attribute} = self.encrypted_#{attribute}
end
@#{attribute}
@@ -40,7 +40,7 @@ def #{attribute}
# Set the un-encrypted attribute
# Also updates the encrypted field with the encrypted value
def #{attribute}=(value)
- self.encrypted_#{attribute} = @stored_encrypted_#{attribute} = ::Symmetric::Encryption.encrypt(value#{".to_yaml" if options[:marshal]})
+ self.encrypted_#{attribute} = @stored_encrypted_#{attribute} = ::SymmetricEncryption.encrypt(value#{".to_yaml" if options[:marshal]})
@#{attribute} = value
end
UNENCRYPTED
@@ -129,7 +129,7 @@ def method_missing_with_attr_encrypted(method, *args, &block)
attribute_names.each_with_index do |attribute, index|
encrypted_name = "encrypted_#{attribute}"
if instance_methods.include? encrypted_name #.to_sym in 1.9
- args[index] = ::Symmetric::Encryption.encrypt(args[index])
+ args[index] = ::SymmetricEncryption.encrypt(args[index])
attribute_names[index] = encrypted_name
end
end
View
16 lib/symmetric/extensions/mongoid/fields.rb → ...c_encryption/extensions/mongoid/fields.rb
@@ -16,8 +16,8 @@ module ClassMethods
# Mongoid.logger = Logger.new($stdout)
# Mongoid.load!('config/mongoid.yml')
#
- # # Initialize Symmetric::Encryption in a standalone environment. In a Rails app this is not required
- # Symmetric::Encryption.load!('config/symmetric-encryption.yml', 'test')
+ # # Initialize SymmetricEncryption in a standalone environment. In a Rails app this is not required
+ # SymmetricEncryption.load!('config/symmetric-encryption.yml', 'test')
#
# class Person
# include Mongoid::Document
@@ -44,13 +44,13 @@ module ClassMethods
# puts "Decrypted Social Security Number is: #{person.social_security_number}"
#
# # Or is the same as
- # puts "Decrypted Social Security Number is: #{Symmetric::Encryption.decrypt(person.encrypted_social_security_number)}"
+ # puts "Decrypted Social Security Number is: #{SymmetricEncryption.decrypt(person.encrypted_social_security_number)}"
#
# # Sets the encrypted_social_security_number to encrypted version
# person.social_security_number = "123456789"
#
# # Or, is equivalent to:
- # person.social_security_number = Symmetric::Encryption.encrypt("123456789")
+ # person.social_security_number = SymmetricEncryption.encrypt("123456789")
#
#
# Note: Unlike attr_encrypted finders must use the encrypted field name
@@ -78,7 +78,7 @@ def field_with_symmetric_encryption(field_name, options={})
if options.delete(:encrypted) == true
decrypt_as = options.delete(:decrypt_as)
unless decrypt_as
- raise "Symmetric::Encryption for Mongoid. When encryption is enabled for a field it must either start with 'encrypted_' or the option :decrypt must be supplied" unless field_name.to_s.start_with?('encrypted_')
+ raise "SymmetricEncryption for Mongoid. When encryption is enabled for a field it must either start with 'encrypted_' or the option :decrypt must be supplied" unless field_name.to_s.start_with?('encrypted_')
decrypt_as = field_name.to_s['encrypted_'.length..-1]
end
@@ -86,7 +86,7 @@ def field_with_symmetric_encryption(field_name, options={})
underlying_type = options[:type]
options[:type] = String
- raise "Symmetric::Encryption for Mongoid currently only supports :type => String" unless underlying_type == String
+ raise "SymmetricEncryption for Mongoid currently only supports :type => String" unless underlying_type == String
# #TODO Need to do type conversions. Currently only support String
@@ -95,7 +95,7 @@ def field_with_symmetric_encryption(field_name, options={})
# Set the un-encrypted bank account number
# Also updates the encrypted field with the encrypted value
def #{decrypt_as}=(value)
- @stored_#{field_name} = Symmetric::Encryption.encrypt(value)
+ @stored_#{field_name} = SymmetricEncryption.encrypt(value)
self.#{field_name} = @stored_#{field_name}
@#{decrypt_as} = value
end
@@ -105,7 +105,7 @@ def #{decrypt_as}=(value)
# If this method is not called, then the encrypted value is never decrypted
def #{decrypt_as}
if @stored_#{field_name} != self.#{field_name}
- @#{decrypt_as} = Symmetric::Encryption.decrypt(self.#{field_name})
+ @#{decrypt_as} = SymmetricEncryption.decrypt(self.#{field_name})
@stored_#{field_name} = self.#{field_name}
end
@#{decrypt_as}
View
4 lib/symmetric/railtie.rb → lib/symmetric_encryption/railtie.rb
@@ -1,5 +1,5 @@
# encoding: utf-8
-module Symmetric #:nodoc:
+module SymmetricEncryption #:nodoc:
class Railtie < Rails::Railtie #:nodoc:
# Exposes Symmetric Encryption's configuration to the Rails application configuration.
@@ -31,7 +31,7 @@ class Railtie < Rails::Railtie #:nodoc:
initializer "symmetric-encryption.initialize" , :before=>"active_record.initialize_database" do
config_file = Rails.root.join("config", "symmetric-encryption.yml")
if config_file.file?
- ::Symmetric::Encryption.load!(config_file, Rails.env)
+ ::SymmetricEncryption.load!(config_file, Rails.env)
else
puts "\nSymmetric Encryption config not found. Create a config file at: config/symmetric-encryption.yml"
# puts "to generate one run: rails generate symmetric-encryption:config\n\n"
View
10 ...metric/railties/symmetric_encryption.rake → ...yption/railties/symmetric_encryption.rake
@@ -3,7 +3,7 @@ namespace :symmetric_encryption do
desc 'Decrypt the supplied string. Example: VALUE="_encrypted_string_" rake symmetric_encryption:decrypt'
task :decrypt => :environment do
puts "\nEncrypted: #{ENV['VALUE']}"
- puts "Decrypted: #{Symmetric::Encryption.decrypt(ENV['VALUE'])}\n\n"
+ puts "Decrypted: #{SymmetricEncryption.decrypt(ENV['VALUE'])}\n\n"
end
desc 'Encrypt a value, such as a password. Example: rake symmetric_encryption:encrypt'
@@ -20,19 +20,19 @@ namespace :symmetric_encryption do
puts "Passwords do not match, please try again"
end
end
- puts "\nEncrypted: #{Symmetric::Encryption.encrypt(password1)}\n\n"
+ puts "\nEncrypted: #{SymmetricEncryption.encrypt(password1)}\n\n"
end
desc 'Generate new Symmetric key and initialization vector. Example: RAILS_ENV=production rake symmetric_encryption:generate_symmetric_keys'
task :generate_symmetric_keys do
- Symmetric::Encryption.generate_symmetric_key_files
+ SymmetricEncryption.generate_symmetric_key_files
end
desc 'Generate a random password and display its encrypted form. Example: rake symmetric_encryption:random_password'
task :random_password => :environment do
- p = Symmetric::Encryption.random_password
+ p = SymmetricEncryption.random_password
puts "\nGenerated Password: #{p}"
- puts "Encrypted: #{Symmetric::Encryption.encrypt(p)}\n\n"
+ puts "Encrypted: #{SymmetricEncryption.encrypt(p)}\n\n"
end
end
View
8 ...railties/symmetric_encrypted_validator.rb → ...ailties/symmetric_encryption_validator.rb
@@ -2,17 +2,17 @@
#
# Example:
# class MyModel < ActiveRecord::Base
-# validates :encrypted_ssn, :symmetric_encrypted => true
+# validates :encrypted_ssn, :symmetric_encryption => true
# end
#
# m = MyModel.new
# m.valid?
# # => false
-# m.encrypted_ssn = Symmetric::Encryption.encrypt('123456789')
+# m.encrypted_ssn = SymmetricEncryption.encrypt('123456789')
# m.valid?
# # => true
-class SymmetricEncryptedValidator < ActiveModel::EachValidator
+class SymmetricEncryptionValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
- record.errors.add(attribute, "must be a value encrypted using Symmetric::Encryption.encrypt") unless Symmetric::Encryption.encrypted?(value)
+ record.errors.add(attribute, "must be a value encrypted using SymmetricEncryption.encrypt") unless SymmetricEncryption.encrypted?(value)
end
end
View
81 lib/symmetric/encryption_reader.rb → lib/symmetric_encryption/reader.rb
@@ -1,40 +1,38 @@
-module Symmetric
- class EncryptionReader
- # Read from encrypted files and other IO streams
- #
- # Features:
- # * Decryption on the fly whilst reading files
- # * Large file support by only buffering small amounts of data in memory
- #
- # # Example: Read and decrypt a line at a time from a file
- # Symmetric::EncryptionReader.open('test_file') do |file|
- # file.each_line {|line| p line }
- # end
- #
- # # Example: Read and decrypt entire file in memory
- # # Not recommended for large files
- # Symmetric::EncryptionReader.open('test_file') {|f| f.read }
- #
- # # Example: Reading a limited number of bytes at a time from the file
- # Symmetric::EncryptionReader.open('test_file') do |file|
- # file.read(1)
- # file.read(5)
- # file.read
- # end
- #
- # # Example: Read and decrypt 5 bytes at a time until the end of file is reached
- # Symmetric::EncryptionReader.open('test_file') do |file|
- # while !file.eof? do
- # file.read(5)
- # end
- # end
- #
- # # Example: Read, Unencrypt and decompress data in a file
- # Symmetric::EncryptionReader.open('encrypted_compressed.zip', :compress => true) do |file|
- # file.each_line {|line| p line }
- # end
-
-
+module SymmetricEncryption
+ # Read from encrypted files and other IO streams
+ #
+ # Features:
+ # * Decryption on the fly whilst reading files
+ # * Large file support by only buffering small amounts of data in memory
+ #
+ # # Example: Read and decrypt a line at a time from a file
+ # SymmetricEncryption::Reader.open('test_file') do |file|
+ # file.each_line {|line| p line }
+ # end
+ #
+ # # Example: Read and decrypt entire file in memory
+ # # Not recommended for large files
+ # SymmetricEncryption::Reader.open('test_file') {|f| f.read }
+ #
+ # # Example: Reading a limited number of bytes at a time from the file
+ # SymmetricEncryption::Reader.open('test_file') do |file|
+ # file.read(1)
+ # file.read(5)
+ # file.read
+ # end
+ #
+ # # Example: Read and decrypt 5 bytes at a time until the end of file is reached
+ # SymmetricEncryption::Reader.open('test_file') do |file|
+ # while !file.eof? do
+ # file.read(5)
+ # end
+ # end
+ #
+ # # Example: Read, Unencrypt and decompress data in a file
+ # SymmetricEncryption::Reader.open('encrypted_compressed.zip', :compress => true) do |file|
+ # file.each_line {|line| p line }
+ # end
+ class Reader
# Open a file for reading, or use the supplied IO Stream
#
# Parameters:
@@ -64,7 +62,6 @@ class EncryptionReader
# Default: 4096
#
# Note: Decryption occurs before decompression
- #
def self.open(filename_or_stream, options={}, &block)
raise "options must be a hash" unless options.respond_to?(:each_pair)
mode = options.fetch(:mode, 'r')
@@ -89,7 +86,7 @@ def initialize(ios,options={})
# Read first block and check for the header
buf = @ios.read(@buffer_size)
- if buf.start_with?(Symmetric::Encryption::MAGIC_HEADER)
+ if buf.start_with?(SymmetricEncryption::MAGIC_HEADER)
# Header includes magic header and version byte
# Remove header and extract flags
header, flags = buf.slice!(0..MAGIC_HEADER_SIZE).unpack(MAGIC_HEADER_UNPACK)
@@ -100,8 +97,8 @@ def initialize(ios,options={})
end
# Use primary cipher by default, but allow a secondary cipher to be selected for encryption
- @cipher = Encryption.cipher(@version)
- raise "Cipher with version:#{@version} not found in any of the configured Symmetric::Encryption ciphers" unless @cipher
+ @cipher = SymmetricEncryption.cipher(@version)
+ raise "Cipher with version:#{@version} not found in any of the configured SymmetricEncryption ciphers" unless @cipher
@stream_cipher = @cipher.send(:openssl_cipher, :decrypt)
# First call to #update should return an empty string anyway
@@ -119,7 +116,7 @@ def initialize(ios,options={})
# Returns nil when the header is not present in the stream
#
# Note: The file will not be decompressed automatically when compressed.
- # To decompress the data automatically call Symmetric::Encryption.open
+ # To decompress the data automatically call SymmetricEncryption.open
def compressed?
@compressed
end
View
280 lib/symmetric_encryption/symmetric_encryption.rb
@@ -0,0 +1,280 @@
+require 'base64'
+require 'openssl'
+require 'zlib'
+require 'yaml'
+
+# Encrypt using 256 Bit AES CBC symmetric key and initialization vector
+# The symmetric key is protected using the private key below and must
+# be distributed separately from the application
+module SymmetricEncryption
+
+ # Defaults
+ @@cipher = nil
+ @@secondary_ciphers = []
+
+ # Set the Primary Symmetric Cipher to be used
+ def self.cipher=(cipher)
+ raise "Cipher must be similar to SymmetricEncryption::Ciphers" unless cipher.respond_to?(:encrypt) && cipher.respond_to?(:decrypt)
+ @@cipher = cipher
+ end
+
+ # Returns the Primary Symmetric Cipher being used
+ # If a version is supplied, then the cipher matching that version will be
+ # returned or nil if no match was found
+ def self.cipher(version = nil)
+ return @@cipher if version.nil? || (@@cipher.version == version)
+ secondary_ciphers.find {|c| c.version == version}
+ end
+
+ # Set the Secondary Symmetric Ciphers Array to be used
+ def self.secondary_ciphers=(secondary_ciphers)
+ raise "secondary_ciphers must be a collection" unless secondary_ciphers.respond_to? :each
+ secondary_ciphers.each do |cipher|
+ raise "secondary_ciphers can only consist of SymmetricEncryption::Ciphers" unless cipher.respond_to?(:encrypt) && cipher.respond_to?(:decrypt)
+ end
+ @@secondary_ciphers = secondary_ciphers
+ end
+
+ # Returns the Primary Symmetric Cipher being used
+ def self.secondary_ciphers
+ @@secondary_ciphers
+ end
+
+ # AES Symmetric Decryption of supplied string
+ # Returns decrypted string
+ # Returns nil if the supplied str is nil
+ # Returns "" if it is a string and it is empty
+ #
+ # Note: If secondary ciphers are supplied in the configuration file the
+ # first key will be used to decrypt 'str'. If it fails each cipher in the
+ # order supplied will be tried.
+ # It is slow to try each cipher in turn, so should be used during migrations
+ # only
+ #
+ # Raises: OpenSSL::Cipher::CipherError when 'str' was not encrypted using
+ # the supplied key and iv
+ #
+ def self.decrypt(str)
+ raise "Call SymmetricEncryption.load! or SymmetricEncryption.cipher= prior to encrypting or decrypting data" unless @@cipher
+ binary = ::Base64.decode64(str) if str
+ begin
+ @@cipher.decrypt(binary)
+ rescue OpenSSL::Cipher::CipherError => exc
+ @@secondary_ciphers.each do |cipher|
+ begin
+ return cipher.decrypt(binary)
+ rescue OpenSSL::Cipher::CipherError
+ end
+ end
+ raise exc
+ end
+ end
+
+ # AES Symmetric Encryption of supplied string
+ # Returns result as a Base64 encoded string
+ # Returns nil if the supplied str is nil
+ # Returns "" if it is a string and it is empty
+ def self.encrypt(str)
+ raise "Call SymmetricEncryption.load! or SymmetricEncryption.cipher= prior to encrypting or decrypting data" unless @@cipher
+
+ # Encrypt data as a binary string
+ result = @@cipher.encrypt(str)
+
+ # Base 64 Encoding of binary data
+ result = ::Base64.encode64(result) if result
+ result
+ end
+
+ # Invokes decrypt
+ # Returns decrypted String
+ # Return nil if it fails to decrypt a String
+ #
+ # Useful for example when decoding passwords encrypted using a key from a
+ # different environment. I.e. We cannot decode production passwords
+ # in the test or development environments but still need to be able to load
+ # YAML config files that contain encrypted development and production passwords
+ def self.try_decrypt(str)
+ raise "Call SymmetricEncryption.load! or SymmetricEncryption.cipher= prior to encrypting or decrypting data" unless @@cipher
+ begin
+ decrypt(str)
+ rescue OpenSSL::Cipher::CipherError
+ nil
+ end
+ end
+
+ # Returns [true|false] as to whether the data could be decrypted
+ # Parameters:
+ # encrypted_data: Encrypted string
+ def self.encrypted?(encrypted_data)
+ raise "Call SymmetricEncryption.load! or SymmetricEncryption.cipher= prior to encrypting or decrypting data" unless @@cipher
+
+ # First make sure Base64 encoded data still ends with "\n" since it could be used in a key field somewhere
+ return false unless encrypted_data.end_with?("\n")
+
+ # For now have to decrypt it fully
+ !try_decrypt(encrypted_data).nil?
+ end
+
+ # Load the Encryption Configuration from a YAML file
+ # filename:
+ # Name of file to read.
+ # Mandatory for non-Rails apps
+ # Default: Rails.root/config/symmetric-encryption.yml
+ # environment:
+ # Which environments config to load. Usually: production, development, etc.
+ # Default: Rails.env
+ def self.load!(filename=nil, environment=nil)
+ config = read_config(filename, environment)
+
+ # Check for hard coded key, iv and cipher
+ if config[:key]
+ @@cipher = Cipher.new(config)
+ @@secondary_ciphers = []
+ else
+ private_rsa_key = config[:private_rsa_key]
+ @@cipher, *@@secondary_ciphers = config[:ciphers].collect do |cipher_conf|
+ cipher_from_encrypted_files(
+ private_rsa_key,
+ cipher_conf[:cipher],
+ cipher_conf[:key_filename],
+ cipher_conf[:iv_filename])
+ end
+ end
+
+ true
+ end
+
+ # Future: Generate private key in config file generator
+ #new_key = OpenSSL::PKey::RSA.generate(2048)
+
+ # Generate new random symmetric keys for use with this Encryption library
+ #
+ # Note: Only the current Encryption key settings are used
+ #
+ # Creates Symmetric Key .key
+ # and initilization vector .iv
+ # which is encrypted with the above Public key
+ #
+ # Warning: Existing files will be overwritten
+ def self.generate_symmetric_key_files(filename=nil, environment=nil)
+ config = read_config(filename, environment)
+ cipher_cfg = config[:ciphers].first
+ key_filename = cipher_cfg[:key_filename]
+ iv_filename = cipher_cfg[:iv_filename]
+ cipher = cipher_cfg[:cipher]
+
+ raise "The configuration file must contain a 'private_rsa_key' parameter to generate symmetric keys" unless config[:private_rsa_key]
+ rsa_key = OpenSSL::PKey::RSA.new(config[:private_rsa_key])
+
+ # Generate a new Symmetric Key pair
+ key_pair = SymmetricEncryption::Cipher.random_key_pair(cipher || 'aes-256-cbc', !iv_filename.nil?)
+
+ # Save symmetric key after encrypting it with the private RSA key, backing up existing files if present
+ File.rename(key_filename, "#{key_filename}.#{Time.now.to_i}") if File.exist?(key_filename)
+ File.open(key_filename, 'wb') {|file| file.write( rsa_key.public_encrypt(key_pair[:key]) ) }
+
+ if iv_filename
+ File.rename(iv_filename, "#{iv_filename}.#{Time.now.to_i}") if File.exist?(iv_filename)
+ File.open(iv_filename, 'wb') {|file| file.write( rsa_key.public_encrypt(key_pair[:iv]) ) }
+ end
+ puts("Generated new Symmetric Key for encryption. Please copy #{key_filename} and #{iv_filename} to the other web servers in #{environment}.")
+ end
+
+ # Generate a 22 character random password
+ def self.random_password
+ Base64.encode64(OpenSSL::Cipher.new('aes-128-cbc').random_key)[0..-4]
+ end
+
+ # Binary encrypted data includes this magic header so that we can quickly
+ # identify binary data versus base64 encoded data that does not have this header
+ unless defined? MAGIC_HEADER
+ MAGIC_HEADER = '@EnC'
+ MAGIC_HEADER_SIZE = MAGIC_HEADER.size
+ MAGIC_HEADER_UNPACK = "A#{MAGIC_HEADER_SIZE}v"
+ end
+
+ protected
+
+ # Returns the Encryption Configuration
+ #
+ # Read the configuration from the YAML file and return in the latest format
+ #
+ # filename:
+ # Name of file to read.
+ # Mandatory for non-Rails apps
+ # Default: Rails.root/config/symmetric-encryption.yml
+ # environment:
+ # Which environments config to load. Usually: production, development, etc.
+ def self.read_config(filename=nil, environment=nil)
+ config = YAML.load_file(filename || File.join(Rails.root, "config", "symmetric-encryption.yml"))[environment || Rails.env]
+
+ # Default cipher
+ default_cipher = config['cipher'] || 'aes-256-cbc'
+ cfg = {}
+
+ # Hard coded symmetric_key? - Dev / Testing use only!
+ if symmetric_key = (config['key'] || config['symmetric_key'])
+ raise "SymmetricEncryption Cannot hard code Production encryption keys in #{filename}" if (environment || Rails.env) == 'production'
+ cfg[:key] = symmetric_key
+ cfg[:iv] = config['iv'] || config['symmetric_iv']
+ cfg[:cipher] = default_cipher
+
+ elsif ciphers = config['ciphers']
+ raise "Missing mandatory config parameter 'private_rsa_key'" unless cfg[:private_rsa_key] = config['private_rsa_key']
+
+ cfg[:ciphers] = ciphers.collect do |cipher_cfg|
+ key_filename = cipher_cfg['key_filename'] || cipher_cfg['symmetric_key_filename']
+ raise "Missing mandatory 'key_filename' for environment:#{environment} in #{filename}" unless key_filename
+ iv_filename = cipher_cfg['iv_filename'] || cipher_cfg['symmetric_iv_filename']
+ {
+ :cipher => cipher_cfg['cipher'] || default_cipher,
+ :key_filename => key_filename,
+ :iv_filename => iv_filename,
+ }
+ end
+
+ else
+ # Migrate old format config
+ raise "Missing mandatory config parameter 'private_rsa_key'" unless cfg[:private_rsa_key] = config['private_rsa_key']
+ cfg[:ciphers] = [ {
+ :cipher => default_cipher,
+ :key_filename => config['symmetric_key_filename'],
+ :iv_filename => config['symmetric_iv_filename'],
+ } ]
+ end
+
+ cfg
+ end
+
+ # Returns an instance of SymmetricEncryption::Cipher initialized from keys
+ # stored in files
+ #
+ # Raises an Exception on failure
+ #
+ # Parameters:
+ # cipher
+ # Encryption cipher for the symmetric encryption key
+ # private_key
+ # Key used to unlock file containing the actual symmetric key
+ # key_filename
+ # Name of file containing symmetric key encrypted using the public
+ # key matching the supplied private_key
+ # iv_filename
+ # Optional. Name of file containing symmetric key initialization vector
+ # encrypted using the public key matching the supplied private_key
+ def self.cipher_from_encrypted_files(private_rsa_key, cipher, key_filename, iv_filename = nil)
+ # Load Encrypted Symmetric keys
+ encrypted_key = File.read(key_filename)
+ encrypted_iv = File.read(iv_filename) if iv_filename
+
+ # Decrypt Symmetric Keys
+ rsa = OpenSSL::PKey::RSA.new(private_rsa_key)
+ iv = rsa.private_decrypt(encrypted_iv) if iv_filename
+ Cipher.new(
+ :key => rsa.private_decrypt(encrypted_key),
+ :iv => iv,
+ :cipher => cipher
+ )
+ end
+
+end
View
4 lib/symmetric_encryption/version.rb
@@ -0,0 +1,4 @@
+# encoding: utf-8
+module SymmetricEncryption #:nodoc
+ VERSION = "0.5.0"
+end
View
12 lib/symmetric/encryption_writer.rb → lib/symmetric_encryption/writer.rb
@@ -1,5 +1,5 @@
-module Symmetric
- class EncryptionWriter
+module SymmetricEncryption
+ class Writer
# Write to encrypted files and other IO streams
#
# Features:
@@ -10,13 +10,13 @@ class EncryptionWriter
# Only the last block in the file will be padded if it is less than the block size
#
# # Example: Encrypt and write data to a file
- # Symmetric::EncryptionWriter.open('test_file') do |file|
+ # SymmetricEncryption::Writer.open('test_file') do |file|
# file.write "Hello World\n"
# file.write "Keep this secret"
# end
#
# # Example: Compress, Encrypt and write data to a file
- # Symmetric::EncryptionWriter.open('encrypted_compressed.zip', :compress => true) do |file|
+ # SymmetricEncryption::Writer.open('encrypted_compressed.zip', :compress => true) do |file|
# file.write "Hello World\n"
# file.write "Compress this\n"
# file.write "Keep this safe and secure\n"
@@ -80,8 +80,8 @@ def initialize(ios,options={})
@compress = options.fetch(:compress, false)
# Use primary cipher by default, but allow a secondary cipher to be selected for encryption
- @cipher = Encryption.cipher(options[:version])
- raise "Cipher with version:#{options[:version]} not found in any of the configured Symmetric::Encryption ciphers" unless @cipher
+ @cipher = SymmetricEncryption.cipher(options[:version])
+ raise "Cipher with version:#{options[:version]} not found in any of the configured SymmetricEncryption ciphers" unless @cipher
@stream_cipher = @cipher.send(:openssl_cipher, :encrypt)
View
14 test/attr_encrypted_test.rb
@@ -27,12 +27,12 @@ class User < ActiveRecord::Base
attr_encrypted :bank_account_number
attr_encrypted :social_security_number
- validates :encrypted_bank_account_number, :symmetric_encrypted => true
- validates :encrypted_social_security_number, :symmetric_encrypted => true
+ validates :encrypted_bank_account_number, :symmetric_encryption => true
+ validates :encrypted_social_security_number, :symmetric_encryption => true
end
# Load Symmetric Encryption keys
-Symmetric::Encryption.load!(File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
+SymmetricEncryption.load!(File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
# Initialize the database connection
config_file = File.join(File.dirname(__FILE__), 'config', 'database.yml')
@@ -44,10 +44,10 @@ class User < ActiveRecord::Base
User.establish_connection(cfg)
#
-# Unit Test for attr_encrypted and validation aspects of Symmetric::Encryption
+# Unit Test for attr_encrypted and validation aspects of SymmetricEncryption
#
class AttrEncryptedTest < Test::Unit::TestCase
- context 'the Symmetric::Encryption Library' do
+ context 'the SymmetricEncryption Library' do
setup do
@bank_account_number = "1234567890"
@@ -159,8 +159,8 @@ class AttrEncryptedTest < Test::Unit::TestCase
assert_equal true, @user.valid?
@user.encrypted_bank_account_number = '123'
assert_equal false, @user.valid?
- assert_equal ["must be a value encrypted using Symmetric::Encryption.encrypt"], @user.errors[:encrypted_bank_account_number]
- @user.encrypted_bank_account_number = Symmetric::Encryption.encrypt('123')
+ assert_equal ["must be a value encrypted using SymmetricEncryption.encrypt"], @user.errors[:encrypted_bank_account_number]
+ @user.encrypted_bank_account_number = SymmetricEncryption.encrypt('123')
assert_equal true, @user.valid?
@user.bank_account_number = '123'
assert_equal true, @user.valid?
View
12 test/cipher_test.rb
@@ -4,15 +4,15 @@
require 'rubygems'
require 'test/unit'
require 'shoulda'
-require 'symmetric/cipher'
+require 'symmetric_encryption/cipher'
-# Unit Test for Symmetric::Cipher
+# Unit Test for SymmetricEncryption::Cipher
#
class CipherTest < Test::Unit::TestCase
context 'standalone' do
should "allow setting the cipher" do
- cipher = Symmetric::Cipher.new(
+ cipher = SymmetricEncryption::Cipher.new(
:cipher => 'aes-128-cbc',
:key => '1234567890ABCDEF1234567890ABCDEF',
:iv => '1234567890ABCDEF'
@@ -21,14 +21,14 @@ class CipherTest < Test::Unit::TestCase
end
should "not require an iv" do
- cipher = Symmetric::Cipher.new(
+ cipher = SymmetricEncryption::Cipher.new(
:key => '1234567890ABCDEF1234567890ABCDEF'
)
assert_equal "\302<\351\227oj\372\3331\310\260V\001\v'\346", cipher.encrypt('Hello World')
end
should "throw an exception on bad data" do
- cipher = Symmetric::Cipher.new(
+ cipher = SymmetricEncryption::Cipher.new(
:cipher => 'aes-128-cbc',
:key => '1234567890ABCDEF1234567890ABCDEF',
:iv => '1234567890ABCDEF'
@@ -42,7 +42,7 @@ class CipherTest < Test::Unit::TestCase
context 'with configuration' do
setup do
- @cipher = Symmetric::Cipher.new(
+ @cipher = SymmetricEncryption::Cipher.new(
:key => '1234567890ABCDEF1234567890ABCDEF',
:iv => '1234567890ABCDEF'
)
View
52 test/encryption_test.rb
@@ -1,52 +0,0 @@
-# Allow examples to be run in-place without requiring a gem install
-$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'
-
-require 'rubygems'
-require 'test/unit'
-require 'shoulda'
-require 'symmetric-encryption'
-
-Symmetric::Encryption.load!(File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
-
-# Unit Test for Symmetric::Encryption
-#
-class EncryptionTest < Test::Unit::TestCase
- context 'initialized' do
-
- context 'Symmetric::Encryption configuration' do
- setup do
- @config = Symmetric::Encryption.send(:read_config, File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
- end
-
- should "match config file" do
- assert_equal @config[:ciphers][0][:cipher], Symmetric::Encryption.cipher.cipher
- end
- end
-
- context 'Symmetric::Encryption tests' do
- setup do
- @social_security_number = "987654321"
- @social_security_number_encrypted = "S+8X1NRrqdfEIQyFHVPuVA==\n"
- @social_security_number_encrypted_with_secondary_1 = "D1UCu38pqJ3jc0GvwJHiow==\n"
- end
-
- should "encrypt simple string" do
- assert_equal @social_security_number_encrypted, Symmetric::Encryption.encrypt(@social_security_number)
- end
-
- should "decrypt string" do
- assert_equal @social_security_number, Symmetric::Encryption.decrypt(@social_security_number_encrypted)
- end
-
- should "determine if string is encrypted" do
- assert_equal true, Symmetric::Encryption.encrypted?(@social_security_number_encrypted)
- assert_equal false, Symmetric::Encryption.encrypted?(@social_security_number)
- end
-
- should "decrypt with secondary key when first one fails" do
- assert_equal @social_security_number, Symmetric::Encryption.decrypt(@social_security_number_encrypted)
- end
- end
- end
-
-end
View
6 test/field_encrypted_test.rb
@@ -30,13 +30,13 @@ class MongoidUser
end
# Load Symmetric Encryption keys
-Symmetric::Encryption.load!(File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
+SymmetricEncryption.load!(File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
#
-# Unit Tests for field encrypted and validation aspects of Symmetric::Encryption
+# Unit Tests for field encrypted and validation aspects of SymmetricEncryption
#
class FieldEncryptedTest < Test::Unit::TestCase
- context 'the Symmetric::Encryption Library' do
+ context 'the SymmetricEncryption Library' do
setup do
@bank_account_number = "1234567890"
@bank_account_number_encrypted = "L94ArJeFlJrZp6SYsvoOGA==\n"
View
20 test/encryption_reader_test.rb → test/reader_test.rb
@@ -6,13 +6,13 @@
require 'shoulda'
require 'symmetric-encryption'
-# Use test keys
-Symmetric::Encryption.cipher = Symmetric::Cipher.new(:key => '1234567890ABCDEF1234567890ABCDEF', :iv=> '1234567890ABCDEF')
+# Load Symmetric Encryption keys
+SymmetricEncryption.load!(File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
-# Unit Test for Symmetric::EncryptedStream
+# Unit Test for SymmetricEncrypted::ReaderStream
#
-class EncryptionReaderTest < Test::Unit::TestCase
- context 'EncryptionReader' do
+class ReaderTest < Test::Unit::TestCase
+ context 'Reader' do
setup do
@data = [
"Hello World\n",
@@ -21,19 +21,19 @@ class EncryptionReaderTest < Test::Unit::TestCase
]
@data_str = @data.inject('') {|sum,str| sum << str}
@data_len = @data_str.length
- @data_encrypted = Symmetric::Encryption.cipher.encrypt(@data_str)
+ @data_encrypted = SymmetricEncryption.cipher.encrypt(@data_str)
@filename = '._test'
end
should "decrypt from string stream as a single read" do
stream = StringIO.new(@data_encrypted)
- decrypted = Symmetric::EncryptionReader.open(stream) {|file| file.read}
+ decrypted = SymmetricEncryption::Reader.open(stream) {|file| file.read}
assert_equal @data_str, decrypted
end
should "decrypt from string stream as a single read, after a partial read" do
stream = StringIO.new(@data_encrypted)
- decrypted = Symmetric::EncryptionReader.open(stream) do |file|
+ decrypted = SymmetricEncryption::Reader.open(stream) do |file|
file.read(10)
file.read
end
@@ -43,7 +43,7 @@ class EncryptionReaderTest < Test::Unit::TestCase
should "decrypt lines from string stream" do
stream = StringIO.new(@data_encrypted)
i = 0
- decrypted = Symmetric::EncryptionReader.open(stream) do |file|
+ decrypted = SymmetricEncryption::Reader.open(stream) do |file|
file.each_line do |line|
assert_equal @data[i], line
i += 1
@@ -54,7 +54,7 @@ class EncryptionReaderTest < Test::Unit::TestCase
should "decrypt fixed lengths from string stream" do
stream = StringIO.new(@data_encrypted)
i = 0
- Symmetric::EncryptionReader.open(stream) do |file|
+ SymmetricEncryption::Reader.open(stream) do |file|
index = 0
[0,10,5,5000].each do |size|
buf = file.read(size)
View
53 test/symmetric_encryption_test.rb
@@ -0,0 +1,53 @@
+# Allow examples to be run in-place without requiring a gem install
+$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'
+
+require 'rubygems'
+require 'test/unit'
+require 'shoulda'
+require 'symmetric-encryption'
+
+# Load Symmetric Encryption keys
+SymmetricEncryption.load!(File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
+
+# Unit Test for SymmetricEncryption
+#
+class SymmetricEncryptionTest < Test::Unit::TestCase
+ context 'initialized' do
+
+ context 'SymmetricEncryption configuration' do
+ setup do
+ @config = SymmetricEncryption.send(:read_config, File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
+ end
+
+ should "match config file" do
+ assert_equal @config[:ciphers][0][:cipher], SymmetricEncryption.cipher.cipher
+ end
+ end
+
+ context 'SymmetricEncryption tests' do
+ setup do
+ @social_security_number = "987654321"
+ @social_security_number_encrypted = "S+8X1NRrqdfEIQyFHVPuVA==\n"
+ @social_security_number_encrypted_with_secondary_1 = "D1UCu38pqJ3jc0GvwJHiow==\n"
+ end
+
+ should "encrypt simple string" do
+ assert_equal @social_security_number_encrypted, SymmetricEncryption.encrypt(@social_security_number)
+ end
+
+ should "decrypt string" do
+ assert_equal @social_security_number, SymmetricEncryption.decrypt(@social_security_number_encrypted)
+ end
+
+ should "determine if string is encrypted" do
+ assert_equal true, SymmetricEncryption.encrypted?(@social_security_number_encrypted)
+ assert_equal false, SymmetricEncryption.encrypted?(@social_security_number)
+ end
+
+ should "decrypt with secondary key when first one fails" do
+ assert_equal @social_security_number, SymmetricEncryption.decrypt(@social_security_number_encrypted)
+ end
+ end
+ end
+
+end
View
12 test/encryption_writer_test.rb → test/writer_test.rb
@@ -6,8 +6,8 @@
require 'shoulda'
require 'symmetric-encryption'
-# Use test keys
-Symmetric::Encryption.cipher = Symmetric::Cipher.new(:key => '1234567890ABCDEF1234567890ABCDEF', :iv=> '1234567890ABCDEF')
+# Load Symmetric Encryption keys
+SymmetricEncryption.load!(File.join(File.dirname(__FILE__), 'config', 'symmetric-encryption.yml'), 'test')
# Unit Test for Symmetric::EncryptedStream
#
@@ -21,13 +21,13 @@ class EncryptionWriterTest < Test::Unit::TestCase
]
@data_str = @data.inject('') {|sum,str| sum << str}
@data_len = @data_str.length
- @data_encrypted = Symmetric::Encryption.cipher.encrypt(@data_str)
+ @data_encrypted = SymmetricEncryption.cipher.encrypt(@data_str)
@filename = '._test'
end
should "encrypt to string stream" do
stream = StringIO.new
- file = Symmetric::EncryptionWriter.new(stream)
+ file = SymmetricEncryption::Writer.new(stream)
written_len = @data.inject(0) {|sum,str| sum + file.write(str)}
file.close
@@ -38,7 +38,7 @@ class EncryptionWriterTest < Test::Unit::TestCase
should "encrypt to string stream using .open" do
written_len = 0
stream = StringIO.new
- Symmetric::EncryptionWriter.open(stream) do |file|
+ SymmetricEncryption::Writer.open(stream) do |file|
written_len = @data.inject(0) {|sum,str| sum + file.write(str)}
end
assert_equal @data_len, written_len
@@ -46,7 +46,7 @@ class EncryptionWriterTest < Test::Unit::TestCase
should "encrypt to file using .open" do
written_len = nil
- Symmetric::EncryptionWriter.open(@filename) do |file|
+ SymmetricEncryption::Writer.open(@filename) do |file|
written_len = @data.inject(0) {|sum,str| sum + file.write(str)}
end
assert_equal @data_len, written_len
Please sign in to comment.
Something went wrong with that request. Please try again.