def self.encrypt plaintext
unless defined?(GPGME)
raise RecoverableError, "Encryption is only supported when using the 'gpgme' gem"
end
GPGME::Engine.home_dir = self.gnupghome
ctx = GPGME::Ctx.new
recipients = self.find_recipients
debug("Recipents are #{recipients}")
raise RecoverableError, 'No recipients provided, don\'t know who to encrypt to' if recipients.empty?
keys = recipients.map {|r|
key_to_use = ctx.keys(r).first
if key_to_use.nil?
raise RecoverableError, "No key found on keyring for #{r}"
end
key_to_use
}
debug("Keys: #{keys}")
always_trust = self.option(:always_trust)
unless always_trust
keys.each do |key|
unless key.primary_uid.validity >= GPGME::VALIDITY_FULL
raise RecoverableError, "Key #{key.sha} (#{key.email}) not trusted (if key trust is established by another means then specify always-trust)"
end
end
end
data = GPGME::Data.from_str(plaintext)
crypto = GPGME::Crypto.new(:always_trust => always_trust)
ciphertext = crypto.encrypt(data, :recipients => keys)
ciphertext.seek 0
ciphertext.read
end