0

我正在使用 GPGME...我需要一个关于使用gpgme_passphrase_cb_tgpgme_set_passphrase_cb功能的示例,因为我不明白如何创建一个gpgme_passphrase_cb_t.

4

1 回答 1

2

这是来自 gpgme++ 的代码,它将基于回调的接口包装到 C++ 接口中:

界面:

class PassphraseProvider {
public:
  virtual ~PassphraseProvider() {}

  virtual char * getPassphrase( const char * useridHint,
                                const char * description,
                                bool previousWasBad,
                                bool & canceled ) = 0;
};

该函数应该显示description为提示,并返回输入的密码(缓冲区必须是malloc()ed)。它也可以设置canceledtrue指示用户中止。参数useridHintpreviousWasBad只是附加信息。

这是通用回调:

// Code taken from gpgme++, license: LGPLv2+
static
gpgme_error_t passphrase_callback( void * opaque, const char * uid_hint, const char * desc,
                                   int prev_was_bad, int fd ) {
  PassphraseProvider * provider = static_cast<PassphraseProvider*>( opaque );
  bool canceled = false;
  gpgme_error_t err = GPG_ERR_NO_ERROR;
  char * passphrase = provider ? provider->getPassphrase( uid_hint, desc, prev_was_bad, canceled ) : 0 ;
  if ( canceled )
    err = make_error( GPG_ERR_CANCELED );
  else
    if ( passphrase && *passphrase ) {
      size_t passphrase_length = std::strlen( passphrase );
      size_t written = 0;
      do {
#ifdef HAVE_GPGME_IO_READWRITE
        ssize_t now_written = gpgme_io_write( fd, passphrase + written, passphrase_length - written );
#else
        ssize_t now_written = write( fd, passphrase + written, passphrase_length - written );
#endif
        if ( now_written < 0 ) {
          err = make_err_from_syserror();
          break;
        }
        written += now_written;
      } while ( written < passphrase_length );
    }

  free( passphrase );
#ifdef HAVE_GPGME_IO_READWRITE
  gpgme_io_write( fd, "\n", 1 );
#else
  write( fd, "\n", 1 );
#endif
  return err;
}

给定接口的实现ppPassphraseProvider您可以像这样将所有内容联系在一起:

gpgme_set_passphrase_cb( ctx, &passphrase_callback, pp );
于 2011-04-26T13:29:44.713 回答