Created
January 15, 2019 04:24
-
-
Save binford2k/4e1e130a5a243b251364afc17cd40eb8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'puppet' | |
Puppet.initialize_settings | |
def encrypt(data, destination) | |
certpath = Puppet.settings[:cacert] | |
keypath = Puppet.settings[:cakey] | |
destpath = "#{Puppet.settings[:signeddir]}/#{destination}.pem" | |
cert = OpenSSL::X509::Certificate.new(File.read(certpath)) | |
# A dummy password with at least 4 characters is required here | |
# since Ruby 2.4 which enforces a minimum password length | |
# of 4 bytes. This is true even if the key has no password | |
# at all--in which case the password we supply is ignored. | |
# We can pass in a dummy here, since we know the certificate | |
# has no password. | |
key = OpenSSL::PKey::RSA.new(File.read(keypath), '1234') | |
target = OpenSSL::X509::Certificate.new(File.read(destpath)) | |
signed = OpenSSL::PKCS7::sign(cert, key, data, [], OpenSSL::PKCS7::BINARY) | |
cipher = OpenSSL::Cipher::new("AES-128-CFB") | |
OpenSSL::PKCS7::encrypt([target], signed.to_der, cipher, OpenSSL::PKCS7::BINARY).to_s | |
end | |
def decrypt(data) | |
raise ArgumentError, 'Can only decrypt strings' unless data.class == String | |
cert = OpenSSL::X509::Certificate.new(File.read(Puppet.settings[:hostcert])) | |
# Same dummy password as above. | |
key = OpenSSL::PKey::RSA.new(File.read(Puppet.settings[:hostprivkey]), '1234') | |
source = OpenSSL::X509::Certificate.new(File.read(Puppet.settings[:localcacert])) | |
store = OpenSSL::X509::Store.new | |
store.add_cert(source) | |
blob = OpenSSL::PKCS7.new(data) | |
decrypted = blob.decrypt(key, cert) | |
verified = OpenSSL::PKCS7.new(decrypted) | |
unless verified.verify(nil, store, nil, OpenSSL::PKCS7::NOVERIFY) | |
raise ArgumentError, 'Signature verification failed' | |
end | |
verified.data | |
end | |
phrase = 'hello world' | |
dest = 'ben.ford-c02nq2h2g3qt' | |
raise 'it broke' unless decrypt(encrypt(phrase, dest)) == phrase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment