From 3e5e1b15f5f15ce6cbd717e217b62f7b34742f48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix-Antoine=20Fortin?= Date: Mon, 6 May 2024 10:03:32 -0400 Subject: [PATCH 1/2] Add support to encrypt with an RSA public key Based on the header of the public key, we can identify if we have a X509 certificate or an RSA public key. If we have an RSA public key, we simply generate a X509 certificate on the fly that will contain only the information required by encrypt. --- lib/hiera/backend/eyaml/encryptors/pkcs7.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/hiera/backend/eyaml/encryptors/pkcs7.rb b/lib/hiera/backend/eyaml/encryptors/pkcs7.rb index 025eccf..95fbf0e 100644 --- a/lib/hiera/backend/eyaml/encryptors/pkcs7.rb +++ b/lib/hiera/backend/eyaml/encryptors/pkcs7.rb @@ -37,7 +37,13 @@ def self.encrypt(plaintext) LoggingHelper.trace 'PKCS7 encrypt' public_key_pem = load_public_key_pem - public_key_x509 = OpenSSL::X509::Certificate.new(public_key_pem) + if public_key_pem.include? 'BEGIN CERTIFICATE' + public_key_x509 = OpenSSL::X509::Certificate.new(public_key_pem) + elsif public_key_pem.include? 'BEGIN PUBLIC KEY' + public_key_rsa = OpenSSL::PKey::RSA.new(public_key_pem) + public_key_x509 = OpenSSL::X509::Certificate.new + public_key_x509.public_key = public_key_rsa.public_key + end cipher = OpenSSL::Cipher.new('aes-256-cbc') OpenSSL::PKCS7.encrypt([public_key_x509], plaintext, cipher, OpenSSL::PKCS7::BINARY).to_der From 87544abb7404ff8e63770ce489bad4e7513b4460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix-Antoine=20Fortin?= Date: Wed, 8 May 2024 09:02:27 -0400 Subject: [PATCH 2/2] Raise error when public key is invalid --- lib/hiera/backend/eyaml/encryptors/pkcs7.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/hiera/backend/eyaml/encryptors/pkcs7.rb b/lib/hiera/backend/eyaml/encryptors/pkcs7.rb index 95fbf0e..f17e5f9 100644 --- a/lib/hiera/backend/eyaml/encryptors/pkcs7.rb +++ b/lib/hiera/backend/eyaml/encryptors/pkcs7.rb @@ -43,6 +43,8 @@ def self.encrypt(plaintext) public_key_rsa = OpenSSL::PKey::RSA.new(public_key_pem) public_key_x509 = OpenSSL::X509::Certificate.new public_key_x509.public_key = public_key_rsa.public_key + else + raise StandardError, "file #{public_key_pem} cannot be used to encrypt - invalid public key format" end cipher = OpenSSL::Cipher.new('aes-256-cbc')