lib/symmetric_encryption/cipher.rb in symmetric-encryption-4.1.0.beta1 vs lib/symmetric_encryption/cipher.rb in symmetric-encryption-4.1.0
- old
+ new
@@ -131,12 +131,14 @@
# * Should only be used for large strings since compression overhead and
# the overhead of adding the encryption header may exceed any benefits of
# compression
def encrypt(str, random_iv: false, compress: false, header: always_add_header)
return if str.nil?
+
str = str.to_s
return str if str.empty?
+
encrypted = binary_encrypt(str, random_iv: random_iv, compress: compress, header: header)
encode(encrypted)
end
# Decode and Decrypt string
@@ -159,10 +161,11 @@
def decrypt(str)
decoded = decode(str)
return unless decoded
return decoded if decoded.empty?
+
decrypted = binary_decrypt(decoded)
# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary
decrypted.force_encoding(SymmetricEncryption::BINARY_ENCODING) unless decrypted.force_encoding(SymmetricEncryption::UTF8_ENCODING).valid_encoding?
@@ -176,19 +179,21 @@
# Note: No encryption or decryption is performed
#
# Returned string is UTF8 encoded except for encoding :none
def encode(binary_string)
return binary_string if binary_string.nil? || (binary_string == '')
+
encoder.encode(binary_string)
end
# Decode the supplied string using the encoding in this cipher instance
# Note: No encryption or decryption is performed
#
# Returned string is Binary encoded
def decode(encoded_string)
return encoded_string if encoded_string.nil? || (encoded_string == '')
+
encoder.decode(encoded_string)
end
# Return a new random key using the configured cipher_name
# Useful for generating new symmetric keys
@@ -241,10 +246,11 @@
# Default: `always_add_header`
#
# See #encrypt to encrypt and encode the result as a string.
def binary_encrypt(str, random_iv: false, compress: false, header: always_add_header)
return if str.nil?
+
string = str.to_s
return string if string.empty?
# Header required when adding a random_iv or compressing
header = Header.new(version: version, compress: compress) if header || random_iv || compress
@@ -298,20 +304,21 @@
# Note:
# When a string is encrypted and the header is used, its decrypted form
# is automatically set to the same UTF-8 or Binary encoding
def binary_decrypt(encrypted_string, header: Header.new)
return if encrypted_string.nil?
+
str = encrypted_string.to_s
str.force_encoding(SymmetricEncryption::BINARY_ENCODING)
return str if str.empty?
offset = header.parse(str)
data = offset.positive? ? str[offset..-1] : str
openssl_cipher = ::OpenSSL::Cipher.new(header.cipher_name || cipher_name)
openssl_cipher.decrypt
- openssl_cipher.key = header.key || @key
- if (iv = header.iv || @iv)
+ openssl_cipher.key = header.key || @key
+ if (iv = header.iv || @iv)
openssl_cipher.iv = iv
end
result = openssl_cipher.update(data)
result << openssl_cipher.final
header.compressed? ? Zlib::Inflate.inflate(result) : result