class ActiveSupport::EncryptedFile
Constants
- CIPHER
Attributes
content_path[R]
env_key[R]
key_path[R]
raise_if_missing_key[R]
Public Class Methods
generate_key()
click to toggle source
# File lib/active_support/encrypted_file.rb, line 24 def self.generate_key SecureRandom.hex(ActiveSupport::MessageEncryptor.key_len(CIPHER)) end
new(content_path:, key_path:, env_key:, raise_if_missing_key:)
click to toggle source
# File lib/active_support/encrypted_file.rb, line 31 def initialize(content_path:, key_path:, env_key:, raise_if_missing_key:) @content_path, @key_path = Pathname.new(content_path), Pathname.new(key_path) @env_key, @raise_if_missing_key = env_key, raise_if_missing_key end
Public Instance Methods
change(&block)
click to toggle source
# File lib/active_support/encrypted_file.rb, line 53 def change(&block) writing read, &block end
key()
click to toggle source
# File lib/active_support/encrypted_file.rb, line 36 def key read_env_key || read_key_file || handle_missing_key end
read()
click to toggle source
# File lib/active_support/encrypted_file.rb, line 40 def read if !key.nil? && content_path.exist? decrypt content_path.binread else raise MissingContentError, content_path end end
write(contents)
click to toggle source
# File lib/active_support/encrypted_file.rb, line 48 def write(contents) IO.binwrite "#{content_path}.tmp", encrypt(contents) FileUtils.mv "#{content_path}.tmp", content_path end
Private Instance Methods
decrypt(contents)
click to toggle source
# File lib/active_support/encrypted_file.rb, line 78 def decrypt(contents) encryptor.decrypt_and_verify contents end
encrypt(contents)
click to toggle source
# File lib/active_support/encrypted_file.rb, line 74 def encrypt(contents) encryptor.encrypt_and_sign contents end
encryptor()
click to toggle source
# File lib/active_support/encrypted_file.rb, line 82 def encryptor @encryptor ||= ActiveSupport::MessageEncryptor.new([ key ].pack("H*"), cipher: CIPHER) end
handle_missing_key()
click to toggle source
# File lib/active_support/encrypted_file.rb, line 95 def handle_missing_key raise MissingKeyError, key_path: key_path, env_key: env_key if raise_if_missing_key end
read_env_key()
click to toggle source
# File lib/active_support/encrypted_file.rb, line 87 def read_env_key ENV[env_key] end
read_key_file()
click to toggle source
# File lib/active_support/encrypted_file.rb, line 91 def read_key_file key_path.binread.strip if key_path.exist? end
writing(contents) { |tmp_path| ... }
click to toggle source
# File lib/active_support/encrypted_file.rb, line 59 def writing(contents) tmp_file = "#{Process.pid}.#{content_path.basename.to_s.chomp('.enc')}" tmp_path = Pathname.new File.join(Dir.tmpdir, tmp_file) tmp_path.binwrite contents yield tmp_path updated_contents = tmp_path.binread write(updated_contents) if updated_contents != contents ensure FileUtils.rm(tmp_path) if tmp_path.exist? end