Search code examples
rubygnupggpgme

Using passphrase callback in ruby gpgme


I am using ruby gpgme gem (1.0.8). My passphrase callback isn't called:

def passfunc(*args)
  fd = args.last
  io = IO.for_fd(fd, 'w')
  io.puts "mypassphrase"
  io.flush
end

opts = {
  :passphrase_callback => method(:passfunc)
}
GPGME.decrypt(input,output, opts)

Does someone have working example of passphrase callback?


Solution

  • Sample of callback you can find in the following working example. It signs a file in detached mode, i.e., the signature file is separated from the original file. It uses the default keyring at ~/.gnupg or something like that. To use a different directory for your keyring, set the environment variable ENV["GNUPGHOME"]="" before call GPGME::sign().

    #!/usr/bin/ruby
    require 'rubygems'
    require 'gpgme'
    
    puts "Signing #{ARGV[0]}" 
    input = File.open(ARGV[0],'r')
    
    PASSWD = "abc"
    
    def passfunc(hook, uid_hint, passphrase_info, prev_was_bad, fd)
        puts("Passphrase for #{uid_hint}: ")
        io = IO.for_fd(fd, 'w')
        io.write(PASSWD+"\n")
        io.flush
    end
    
    output = File.open(ARGV[0]+'.asc','w')
    
    sign = GPGME::sign(input, {
            :passphrase_callback => method(:passfunc), 
            :mode => GPGME::SIG_MODE_DETACH
        })
    output.write(sign)
    output.close
    input.close