Skip to content

Commit

Permalink
#129: Support key decrypting on init for openssl3
Browse files Browse the repository at this point in the history
  • Loading branch information
tobischo committed Jul 31, 2022
1 parent 06f7e63 commit 33d419b
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/epics/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -265,14 +265,16 @@ def dump_keys
JSON.dump(keys.each_with_object({}) {|(k,v),m| m[k]= encrypt(v.key.to_pem)})
end

def cipher
@cipher ||= OpenSSL::Cipher.new("aes-256-cbc")
def new_cipher
# Re-using the cipher between keys has weird behaviours with openssl3
# Using a fresh key instead of memoizing it on the client simplifies things
OpenSSL::Cipher.new('aes-256-cbc')
end

def encrypt(data)
salt = OpenSSL::Random.random_bytes(8)

setup_cipher(:encrypt, self.passphrase, salt)
cipher = setup_cipher(:encrypt, self.passphrase, salt)
Base64.strict_encode64([salt, cipher.update(data) + cipher.final].join)
end

Expand All @@ -281,13 +283,15 @@ def decrypt(data)
salt = data[0..7]
data = data[8..-1]

setup_cipher(:decrypt, self.passphrase, salt)
cipher = setup_cipher(:decrypt, self.passphrase, salt)
cipher.update(data) + cipher.final
end

def setup_cipher(method, passphrase, salt)
cipher = new_cipher
cipher.send(method)
cipher.key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(passphrase, salt, 1, cipher.key_len)
cipher
end

def verify_ssl?
Expand Down

0 comments on commit 33d419b

Please sign in to comment.