2009-12-08 58 views
3

我正在使用ruby gpgme gem(1.0.8)。我的密碼回調不叫:在ruby gpgme中使用密碼回調

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) 

有人有工作示例的密碼短語回調?

回答

3

您可以在以下工作示例中找到回調的示例。它以分離模式簽名文件,即簽名文件與原始文件分離。它使用〜/ .gnupg或類似的默認密鑰環。要爲密鑰環使用不同的目錄,請在調用GPGME :: sign()之前設置環境變量ENV [「GNUPGHOME」] =「」。

#!/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 
3

下面是另一個不使用分離簽名的工作示例。爲了驗證這一點,只需更改 '[email protected]' 你鑰匙的標識,並做到這一點:GPG.decrypt(GPG.encrypt( '一些文本',:護甲=>真))

require 'gpgme' 
require 'highline/import' 

module GPG 
    ENCRYPT_KEY = '[email protected]' 
    @gpg = GPGME::Crypto.new 

    class << self 

    def decrypt(encrypted_data, options = {}) 
     options = { :passphrase_callback => self.method(:passfunc) }.merge(options) 
     @gpg.decrypt(encrypted_data, options).read 
    end 

    def encrypt(data_to_encrypt, options = {}) 
     options = { :passphrase_callback => self.method(:passfunc), :armor => true }.merge(options) 
     @gpg.encrypt(data_to_encrypt, options).read 
    end 

    private 
     def get_passphrase 
     ask("Enter passphrase for #{ENCRYPT_KEY}: ") { |q| q.echo = '*' } 
     end 

     def passfunc(hook, uid_hint, passphrase_info, prev_was_bad, fd) 
     begin 
      system('stty -echo') 
      io = IO.for_fd(fd, 'w') 
      io.puts(get_passphrase) 
      io.flush 
     ensure 
      (0 ... $_.length).each do |i| $_[i] = ?0 end if $_ 
      system('stty echo') 
     end 
     $stderr.puts 
     end 
    end 
end 

乾杯!

- 卡爾

2

需要注意的是和GnuPG 2.0(在1.4時use-agent選項時)pinentry用於密碼收集是非常重要的。這意味着gpgme密碼回調將爲not be invoked。這被描述爲here,並且可以在gpgme-toolexample中找到使用的示例。

+0

非常感謝你 – msanteler 2015-03-10 21:44:56