Permalink
Browse files

incorporate feedback on cleaner code, encrytable? method

  • Loading branch information...
1 parent aadef33 commit 6e00a9938edf956c37b5263331163e4edc4383d2 @Capncavedan Capncavedan committed Mar 9, 2013
Showing with 34 additions and 13 deletions.
  1. +20 −9 lib/crypt_keeper/provider/aes.rb
  2. +14 −4 spec/provider/aes_spec.rb
@@ -27,9 +27,7 @@ def initialize(options = {})
raise ArgumentError, "Missing :key"
end
- @strict_mode = options.fetch(:strict_mode) do
- @strict_mode = true
- end
+ @strict_mode = options.fetch(:strict_mode, true)
@key = Digest::SHA256.digest(key)
end
@@ -38,27 +36,40 @@ def initialize(options = {})
#
# Returns a string
def encrypt(value)
- if value == '' && !strict_mode
- value
- else
+ if encryptable?(value)
aes.encrypt
aes.key = key
Base64::encode64("#{aes.random_iv}#{SEPARATOR}#{aes.update(value.to_s) + aes.final}")
+ else
+ value
end
end
# Public: Decrypt a string
#
# Returns a string
def decrypt(value)
- if value == '' && !strict_mode
- value
- else
+ if encryptable?(value)
iv, value = Base64::decode64(value.to_s).split(SEPARATOR)
aes.decrypt
aes.key = key
aes.iv = iv
aes.update(value) + aes.final
+ else
+ value
+ end
+ end
+
+ protected
+
+ # Protected: Determine if value can be encrypted
+ #
+ # Returns a boolean
+ def encryptable?(value)
+ if (value == '' && strict_mode)
+ false
+ else
+ true
end
end
end
View
@@ -23,7 +23,7 @@ module Provider
specify { encrypted.should_not == 'string' }
specify { encrypted.should_not be_blank }
- specify { expect { subject.encrypt('') }.to raise_error(ArgumentError, "data must not be empty") }
+ specify { expect { subject.encrypt('') }.not_to raise_error(ArgumentError) }
end
describe "#decrypt" do
@@ -33,7 +33,12 @@ module Provider
specify { decrypted.should == 'string' }
- specify { expect { subject.decrypt('') }.to raise_error(TypeError, "can't convert nil into String") }
+ specify { expect { subject.decrypt('') }.not_to raise_error(TypeError) }
+ end
+
+ describe "#encryptable?" do
+ specify { subject.send(:encryptable?, '').should be_false }
+ specify { subject.send(:encryptable?, ' ').should be_true }
end
end
@@ -43,11 +48,16 @@ module Provider
its(:strict_mode) { should be_false }
describe "#encrypt" do
- specify { expect { subject.encrypt('') }.not_to raise_error(ArgumentError) }
+ specify { expect { subject.encrypt('') }.to raise_error(ArgumentError) }
end
describe "#decrypt" do
- specify { expect { subject.decrypt('') }.not_to raise_error(TypeError) }
+ specify { expect { subject.decrypt('') }.to raise_error(TypeError) }
+ end
+
+ describe "#encryptable?" do
+ specify { subject.send(:encryptable?, '').should be_true }
+ specify { subject.send(:encryptable?, ' ').should be_true }
end
end
end

0 comments on commit 6e00a99

Please sign in to comment.