Question

This feels like it should be dead simple, yet I'm not having any luck.

The scenario is this: I have a public *.asc key file. I want to use this file (not my personal keyring) to encrypt data on a server, so that I can decrypt it locally with a secret key.

From the command line I can achieve this using gpg, but I'd prefer to use a Ruby library that isn't just a wrapper around the CLI (i.e., presumably one that provides bindings to the C library). I've looked at the GPGME and OpenPGP gems and haven't been able to figure out how to use them. The documentation (especially for OpenPGP) is quite sparse.

Here, for example, is something I've tried using GPGME, without any luck:

key = GPGME::Data.new(File.open(path_to_file))
data = GPGME::Data.new("I want to encrypt this string.")

# Raises GPGME::Error::InvalidValue
GPGME::Ctx.new do |ctx|
  e = ctx.encrypt(key, data)
end

Has anyone been through this already? Surely this can't be that complicated?

Was it helpful?

Solution

I believe I've now got this figured out. It was actually just a few simple pieces I was missing:

  1. Initializing the GPGME::Ctx object with a keylist_mode of GPGME::KEYLIST_MODE_EXTERN.
  2. Importing the public key file using GPGME::Ctx#import.
  3. Using GPGME::Crypto#encrypt to perform the encryption and specifying the correct recipient.

So my solution now looks like this:

key = GPGME::Data.new(File.open(path_to_file))
data = GPGME::Data.new("I want to encrypt this string.")

GPGME::Ctx.new(GPGME::KEYLIST_MODE_EXTERN) do |ctx|
  ctx.import(key)
  crypto = GPGME::Crypto.new(:armor => true, :always_trust => true)
  e = crypto.encrypt(data, :recipients => "recipient@domain.com")
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top