Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request #28139 from stouset/update-secrets-to-use-modern-c…
…rypto

Update secrets to use modern crypto
  • Loading branch information
kaspth committed Mar 2, 2017
2 parents f294e64 + 6aa6f9a commit 0203c37
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 17 deletions.
28 changes: 13 additions & 15 deletions railties/lib/rails/secrets.rb
@@ -1,4 +1,4 @@
require "yaml"
require "active_support/message_encryptor"

module Rails
# Greatly inspired by Ara T. Howard's magnificent sekrets gem. 😘
Expand All @@ -12,6 +12,8 @@ def initialize
end
end

CIPHER = "aes-128-gcm"

@read_encrypted_secrets = false
@root = File # Wonky, but ensures `join` uses the current directory.

Expand All @@ -30,20 +32,22 @@ def parse(paths, env:)
end

def generate_key
cipher = new_cipher
SecureRandom.hex(cipher.key_len)[0, cipher.key_len]
SecureRandom.hex(
OpenSSL::Cipher.new(CIPHER).key_len
)
end

def key
ENV["RAILS_MASTER_KEY"] || read_key_file || handle_missing_key
[(ENV["RAILS_MASTER_KEY"] || read_key_file || handle_missing_key)]
.pack("H*")
end

def encrypt(text)
cipher(:encrypt, text)
def encrypt(data)
encryptor.encrypt_and_sign(data)
end

def decrypt(data)
cipher(:decrypt, data)
encryptor.decrypt_and_verify(data)
end

def read
Expand Down Expand Up @@ -97,14 +101,8 @@ def preprocess(path)
end
end

def new_cipher
OpenSSL::Cipher.new("aes-256-cbc")
end

def cipher(mode, data)
cipher = new_cipher.public_send(mode)
cipher.key = key
cipher.update(data) << cipher.final
def encryptor
@encryptor ||= ActiveSupport::MessageEncryptor.new(key, cipher: CIPHER)
end
end
end
Expand Down
5 changes: 3 additions & 2 deletions railties/test/secrets_test.rb
Expand Up @@ -54,9 +54,10 @@ def teardown

test "reading from key file" do
run_secrets_generator do
File.binwrite("config/secrets.yml.key", "How do I know you feel it?")
key = "00112233445566778899aabbccddeeff"
File.binwrite("config/secrets.yml.key", key)

assert_equal "How do I know you feel it?", Rails::Secrets.key
assert_equal [key].pack("H*"), Rails::Secrets.key
end
end

Expand Down

0 comments on commit 0203c37

Please sign in to comment.