Example #1
0
File: t-data.c Project: gpg/gpgme
void
write_test (round_t round, gpgme_data_t data)
{
  char buffer[1024];
  size_t amt;

  amt = gpgme_data_write (data, text, strlen (text));
  if (amt != strlen (text))
    fail_if_err (gpgme_error_from_errno (errno));

  gpgme_data_seek (data, 0, SEEK_SET);

  if (round == TEST_INOUT_NONE)
    read_once_test (round, data);
  else
    {
      amt = gpgme_data_read (data, buffer, sizeof (buffer));

      if (amt != strlen (text2) || strncmp (buffer, text2, strlen (text2)))
	{
	  fprintf (stderr, "%s:%d: (%i) gpgme_data_read returned wrong data\n",
		   __FILE__, __LINE__, round);
	  exit (1);
	}

      amt = gpgme_data_read (data, buffer, sizeof (buffer));
      if (amt)
	{
	  fprintf (stderr, "%s:%d: (%i) gpgme_data_read did not signal EOF\n",
		   __FILE__, __LINE__, round);
	  exit (1);
	}
    }
}
Example #2
0
gpgme_error_t KGpgMe::readToBuffer(gpgme_data_t in, QByteArray* outBuffer) const
{
	int ret;
	gpgme_error_t err = GPG_ERR_NO_ERROR;

	ret = gpgme_data_seek(in, 0, SEEK_SET);
	if(ret) {
		err = gpgme_err_code_from_errno(errno);
	}
	else {
		char* buf = new char[BUF_SIZE + 2];

		if(buf) {
			while((ret = gpgme_data_read(in, buf, BUF_SIZE)) > 0) {
				uint size = outBuffer->size();
				outBuffer->resize(size + ret);
				memcpy(outBuffer->data() + size, buf, ret);
			}
			if(ret < 0)
				err = gpgme_err_code_from_errno(errno);
			delete[] buf;
		}
	}
	return err;
}
Example #3
0
void *sgpgme_data_release_and_get_mem(gpgme_data_t data, size_t *len)
{
	char buf[BUFSIZ];
	void *result = NULL;
	ssize_t r = 0;
	size_t w = 0;
	
	if (data == NULL)
		return NULL;
	if (len == NULL)
		return NULL;

	/* I know it's deprecated, but we don't compile with _LARGEFILE */
	cm_gpgme_data_rewind(data);
	while ((r = gpgme_data_read(data, buf, BUFSIZ)) > 0) {
		result = realloc(result, r + w);
		if (result == NULL) {
			g_warning("can't allocate memory\n");
			return NULL;
		}
		memcpy(result+w, buf, r);
		w += r;
	}
	
	*len = w;

	gpgme_data_release(data);
	if (r < 0) {
		free(result);
		*len = 0;
		return NULL;
	}
	return result;
}
Example #4
0
File: t-data.c Project: gpg/gpgme
void
read_once_test (round_t round, gpgme_data_t data)
{
  char buffer[1024];
  size_t read;

  read = gpgme_data_read (data, buffer, sizeof (buffer));

  if (read != strlen (text) || strncmp (buffer, text, strlen (text)))
    {
      fprintf (stderr, "%s:%d: (%i) gpgme_data_read returned wrong data\n",
	       __FILE__, __LINE__, round);
      exit (1);
    }

  read = gpgme_data_read (data, buffer, sizeof (buffer));
  if (read)
    {
      fprintf (stderr, "%s:%d: (%i) gpgme_data_read did not signal EOF\n",
	       __FILE__, __LINE__, round);
      exit (1);
    }
}
Example #5
0
JNIEXPORT void JNICALL
Java_com_freiheit_gnupg_GnuPGData_gpgmeDataWrite(JNIEnv * env, jobject self,
						 jlong data, jobject out)
{
    gpgme_error_t err;

    jbyte buf[BUFSIZE];
    size_t nread;

    jclass outputStream = (*env)->GetObjectClass(env, out);
    if (outputStream == NULL) {
        fprintf(stderr, "output stream NULL! abort.\n");
	return;
    }

    jmethodID writeMethod =
	(*env)->GetMethodID(env, outputStream, "write", "([BII)V");
    if (writeMethod == NULL) {
        fprintf(stderr, "write method NULL! abort.\n");
	return;
    }

    jbyteArray jbuf;

    err = (gpgme_data_seek ( DATA(data), (off_t)0, SEEK_SET ) < 0);
    if (UTILS_onErrorThrowException(env, err)) {
	fprintf(stderr, "error throw exception! abort.\n");
	return;
    }

    int size = 0;
    while ((nread = gpgme_data_read(DATA(data), buf, BUFSIZE)) != 0) {
        size += nread;
	jbuf = (*env)->NewByteArray(env, nread);
	if (jbuf == NULL) {
	    fprintf(stderr, "jbuf is NULL! abort.\n");
	    return;
	}
	(*env)->SetByteArrayRegion(env, jbuf, 0, nread, buf);
	(*env)->CallVoidMethod(env, out, writeMethod, jbuf, (jint)0,
			       (jint)nread);
	if ((*env)->ExceptionCheck(env)) {
	    (*env)->DeleteLocalRef(env, jbuf);
	    return;
	}
	(*env)->DeleteLocalRef(env, jbuf);
    }

}
Example #6
0
static void
print_data (gpgme_data_t dh)
{
#define BUF_SIZE 512
  char buf[BUF_SIZE + 1];
  int ret;

  ret = gpgme_data_seek (dh, 0, SEEK_SET);
  if (ret)
    fail_if_err (gpgme_err_code_from_errno (errno));
  while ((ret = gpgme_data_read (dh, buf, BUF_SIZE)) > 0)
    fwrite (buf, ret, 1, stdout);
  if (ret < 0)
    fail_if_err (gpgme_err_code_from_errno (errno));
}
Example #7
0
int read_data(char *buf, int buf_size) {
    int ret;
    strcpy(buf,"");

    if((ret = gpgme_data_read(_cf_out, buf, buf_size)) > 0)
        buf[ret] = '\0';

    if(ret < 0)
        fail_if_err(gpgme_err_code_from_errno(errno));

    if(ret > 0) {
        return 1;
    } else {
        gpgme_data_release(_cf_out);
        return 0;
    }
}
Example #8
0
int cgpg_encrypt(char *nick, char *msg, char buf[], int len, char errmsg[EOF_L_MESSAGE])
{
//   gpgme_error_t gerr;
   gpgme_key_t keyid[2];
   gpgme_data_t plaintext;
   gpgme_data_t encrypted;
   char *p;

   /* retrieve keyid    */
   p = peer_keyid_get(nick);
   if(!p) {
      eof_errmsg("No key-ID registered");
      return 0;
   }

   keyid[1] = NULL;
   printf("encrypting with keyid=%s\n", p);
   if(!cgpg_keyid_get(p, keyid, errmsg)) {
      return 0;
   }
   printf("Key info: %s <%s>\n", keyid[0]->uids->name,  keyid[0]->uids->email);

   /* allocate buffer: non copying!   */
   if(GPG_ERR_NO_ERROR != gpgme_data_new_from_mem(&plaintext, msg, strlen(msg), 0))
      return 0;
   if(GPG_ERR_NO_ERROR != gpgme_data_new(&encrypted)) return 0;

   /* encrypt  buffer   */
   /* FIXME: remove GPGME_ENCRYPT_ALWAYS_TRUST and use trustlevels */
   if(GPG_ERR_NO_ERROR != gpgme_op_encrypt(gpg_context, keyid,
      GPGME_ENCRYPT_ALWAYS_TRUST, plaintext, encrypted)) {
      eof_errmsg("Encryption failed");
      return 0;
   }
   
   /* return result     */
   if(GPG_ERR_NO_ERROR != gpgme_data_seek(encrypted, 0, SEEK_SET)) {
      eof_errmsg("gpgme_data_seek");
      return 0;
   }
   len = gpgme_data_read(encrypted, buf, len);
   buf[len] = '\0';

   return len;
}
Example #9
0
gpgme_error_t
_gpgme_data_outbound_handler (void *opaque, int fd)
{
  struct io_cb_data *data = (struct io_cb_data *) opaque;
  gpgme_data_t dh = (gpgme_data_t) data->handler_value;
  gpgme_ssize_t nwritten;
  TRACE_BEG1 (DEBUG_CTX, "_gpgme_data_outbound_handler", dh,
	      "fd=0x%x", fd);

  if (!dh->pending_len)
    {
      gpgme_ssize_t amt = gpgme_data_read (dh, dh->pending, BUFFER_SIZE);
      if (amt < 0)
	return TRACE_ERR (gpg_error_from_syserror ());
      if (amt == 0)
	{
	  _gpgme_io_close (fd);
	  return TRACE_ERR (0);
	}
      dh->pending_len = amt;
    }

  nwritten = _gpgme_io_write (fd, dh->pending, dh->pending_len);
  if (nwritten == -1 && errno == EAGAIN)
    return TRACE_ERR (0);

  if (nwritten == -1 && errno == EPIPE)
    {
      /* Not much we can do.  The other end closed the pipe, but we
	 still have data.  This should only ever happen if the other
	 end is going to tell us what happened on some other channel.
	 Silently close our end.  */
      _gpgme_io_close (fd);
      return TRACE_ERR (0);
    }

  if (nwritten <= 0)
    return TRACE_ERR (gpg_error_from_syserror ());

  if (nwritten < dh->pending_len)
    memmove (dh->pending, dh->pending + nwritten, dh->pending_len - nwritten);
  dh->pending_len -= nwritten;
  return TRACE_ERR (0);
}
/* Called by gpgme to read data */
static ssize_t
multi_data_read (void *handle, void *buffer, size_t size)
{
    gpgme_data_t data = NULL;
    ssize_t sz = 0;
    GList *datas, *l;
    guchar *buf;

    datas = (GList*)handle;
    buf = (guchar*)buffer;
    
    /* Find first non-null data thingy */
    for (l = datas; l; l = g_list_next (l)) {
        data = (gpgme_data_t)l->data;
        if (data)
            break;
    }
    
    while (size > 0 && data) {
        sz = gpgme_data_read (data, buf, size);
        
        /* An error */
        if (sz < 0)
            return sz;
        
        if (sz > size)
            sz = size;
        
        /* Free current data, get next one */
        if (sz < size) {
            l->data = NULL;
            gpgmex_data_release (data);
            l = g_list_next (l);
            data = (gpgme_data_t)(l ? l->data : NULL);
        }
        
        /* Read later in buffer */
        size -= sz;
        buf += sz;
    }
    
    return sz;
}
QString QalfCrypto::getPublicKey(QString &key) {
	
	// exporting public key
	gpgme_data_t keyData ;
	gpgme_error_t result = gpgme_data_new(&keyData);
	Q_ASSERT(result == GPG_ERR_NO_ERROR) ;

	result = gpgme_op_export(context,key.toLocal8Bit(),0,keyData) ;
	Q_ASSERT(result == GPG_ERR_NO_ERROR) ;
	
	QString publicKeyStr ;
	char  * buffer = (char *) calloc(4096,sizeof(char)) ;
// 	gpgme_data_rewind(keyData) ;
	gpgme_data_seek(keyData,0,SEEK_SET) ;
	gpgme_data_read(keyData,buffer,4096) ;

	publicKeyStr += buffer ;
	return publicKeyStr ;
}
Example #12
0
gpgme_error_t
_gpgme_data_outbound_handler(void *opaque, int fd)
{
    gpgme_data_t dh = (gpgme_data_t) opaque;
    ssize_t nwritten;

    if(!dh->pending_len)
    {
        ssize_t amt = gpgme_data_read(dh, dh->pending, BUFFER_SIZE);
        if(amt < 0)
            return gpg_error_from_errno(errno);
        if(amt == 0)
        {
            _gpgme_io_close(fd);
            return 0;
        }
        dh->pending_len = amt;
    }

    nwritten = _gpgme_io_write(fd, dh->pending, dh->pending_len);
    if(nwritten == -1 && errno == EAGAIN)
        return 0;

    if(nwritten == -1 && errno == EPIPE)
    {
        /* Not much we can do.  The other end closed the pipe, but we
        still have data.  This should only ever happen if the other
         end is going to tell us what happened on some other channel.
         Silently close our end.  */
        _gpgme_io_close(fd);
        return 0;
    }

    if(nwritten <= 0)
        return gpg_error_from_errno(errno);

    if(nwritten < dh->pending_len)
        memmove(dh->pending, dh->pending + nwritten, dh->pending_len - nwritten);
    dh->pending_len -= nwritten;
    return 0;
}
Example #13
0
File: t-data.c Project: gpg/gpgme
void
read_test (round_t round, gpgme_data_t data)
{
  char buffer[1024];
  size_t read;

  if (round == TEST_INOUT_NONE)
    {
      read = gpgme_data_read (data, buffer, sizeof (buffer));
      if (read > 0)
	{
	  fprintf (stderr, "%s:%d: (%i) gpgme_data_read succeeded unexpectedly\n",
		   __FILE__, __LINE__, round);
	  exit (1);
	}
      return;
    }

  read_once_test (round, data);
  gpgme_data_seek (data, 0, SEEK_SET);
  read_once_test (round, data);
}
static gboolean
import_start (SeahorseToolMode *mode, const gchar *uri, gpgme_data_t uridata,
              SeahorsePGPOperation *pop, GError **err)
{
    size_t size;
    SeahorseOperation *op;
    gpgme_error_t gerr;

    /* Start actual import */

    op = SEAHORSE_OPERATION (pop);

    init_crypt();

    buffer = g_malloc0(IMPORT_BUFFER_SIZE); /* Allocate memory for key data */

    size = gpgme_data_read (uridata, (void*) buffer, IMPORT_BUFFER_SIZE);

    if (size > 0) {
        import_proxy_call = dbus_g_proxy_begin_call (dbus_key_proxy, "ImportKeys",
                                                     proxy_call_notification,
                                                     pop, NULL,
                                                     G_TYPE_STRING, "openpgp",
                                                     G_TYPE_STRING, buffer,
                                                     G_TYPE_INVALID);

        seahorse_operation_mark_start (op);
        seahorse_operation_mark_progress (op, _("Importing keys ..."), 0.5);
    } else {
        g_free (buffer);

        gerr = gpgme_err_code_from_errno (errno);
        seahorse_util_gpgme_to_error (gerr, err);
        return FALSE;
    }

    return TRUE;
}
Example #15
0
std::string GPGWrapper::copyData(gpgme_data_t data)
{
    gpgme_error_t error = gpgme_data_rewind(data);
    fail_if_err(error, L"Nie uda³o siê przewin¹æ na pocz¹tek strumienia, aby go póŸniej odczytaæ.");

    const int bufferSize = 4096;
    char buffer[bufferSize + 1];

    gpgme_ssize_t nbytes;
    std::string dataCopy;

    while ((nbytes = gpgme_data_read(data, buffer, bufferSize)) > 0)
    {
        size_t actualLength = dataCopy.length();
        dataCopy.resize(dataCopy.length() + nbytes);
        memcpy(&dataCopy[actualLength], buffer, nbytes);
    }

    if (nbytes == -1)
        throw GPGWrapperError(L"B³¹d podczas kopiowania danyh ze strumienia.");

    return dataCopy;
}
Example #16
0
File: gpg.c Project: comotion/cpm
char* gpgData2Char(gpgme_data_t dh, int* newsize)
  {
    size_t              tmpsize;
    char*               newbuffer;
    char*               tmpbuffer;

    TRACE(99, "gpgData2Char()", NULL);

    newbuffer = NULL;
    *newsize = 0;

    /* we have to rewind the buffer */
    if (gpgme_data_seek(dh, 0, SEEK_SET))
      {
        gpgError(gpgme_err_code_from_errno(errno));
        return NULL;
      }
    tmpbuffer = memAlloc(__FILE__, __LINE__, BUFFERSIZE + 1);
    while ((tmpsize = gpgme_data_read(dh, tmpbuffer, BUFFERSIZE)) > 0)
      {
        newbuffer = memRealloc(__FILE__, __LINE__, newbuffer,
            *newsize, *newsize + tmpsize);

        /* Flawfinder: ignore */
        memcpy(newbuffer + *newsize, tmpbuffer, tmpsize);
        *newsize += tmpsize;
      }
    memFree(__FILE__, __LINE__, tmpbuffer, BUFFERSIZE + 1);
    if (tmpsize < 0)
      {
        gpgError(gpgme_err_code_from_errno(errno));
        return NULL;
      }

    return newbuffer;
  }
Example #17
0
ssize_t GpgME::Data::read( void * buffer, size_t length ) {
  return gpgme_data_read( d->data, buffer, length );
}
Example #18
0
QByteArray GPGME::decryptFile(const QString & filename, QString & keyId, QWidget * parent)
{
    setError(GPG_ERR_NO_ERROR); // clear error
    CallbackData cbData;
    cbData.parent = parent;


    qDebug() << "ERERR" << gpg_err_source(GPG_ERR_CODE_DIM+1);

    gpgme_set_passphrase_cb(p->context, passphraseCallback, &cbData);

    qDebug() << "decrypting file" << filename;
    gpgme_data_t data;
    gpgme_error_t err;

    QFile file(filename);
    if (!file.exists()) {
        setError(GPGME_WRAPPER_ERR_FILE_NOT_FOUND, true);
        return QByteArray();
    }
    if (!file.open(QIODevice::ReadOnly)) {
        setError(GPGME_WRAPPER_ERR_CANNOT_OPEN_FILE, true);
        return QByteArray();
    }
    if (file.size() > FILESIZE_HARD_LIMIT) {
        setError(GPGME_WRAPPER_ERR_FILE_TOO_LARGE, true);
        return QByteArray();
    }

    err = gpgme_data_new_from_fd(&data, file.handle());
    if (err != GPG_ERR_NO_ERROR) {
        setError(err);
        return QByteArray();
    }

    // process data (it's cipher)
    gpgme_data_t plain;
    gpgme_data_new(&plain);
    err = gpgme_op_decrypt(p->context, data, plain);
    // unset passphrase callback
    gpgme_set_passphrase_cb(p->context, 0, 0);
    if (err != GPG_ERR_NO_ERROR) {
        gpgme_data_release(data);
        gpgme_data_release(plain);
        setError(err);
        return QByteArray();
    }

    // decryption is successful so load plain data
    QByteArray resBytes;
    const int bufSize = 1000;
    int read;
    char buf[bufSize];

    gpgme_data_seek(plain, 0, SEEK_SET);
    while (true) {
        read = gpgme_data_read(plain, (void*)buf, bufSize);
        if (read == 0) {
            break;
        }
        if (read == -1) {
            // error, ignore for now
            break;
        }
        resBytes.append(buf, read);
    }

    gpgme_decrypt_result_t decrypt_res = gpgme_op_decrypt_result(p->context);
    gpgme_recipient_t recipient;
    if (decrypt_res) {
        recipient = decrypt_res->recipients;
        while (recipient) {
            keyId = recipient->keyid;
            recipient = recipient->next;
            break; // just ignore the other recipients
        }
    }
    return resBytes;
}
Example #19
0
int main(void) {
    gpgme_check_version (NULL);

    gpgme_error_t err;
    gpgme_data_t plain, cipher;
    gpgme_ctx_t ctx;
    gpgme_key_t recp[2] = { NULL, NULL };
    gpgme_encrypt_flags_t flags = GPGME_ENCRYPT_ALWAYS_TRUST;

    char *plaintext = "foo bar\0";
    char *fp = "845B80B9AD12DB400CE534F6837EED10F97A36A1";
    char *result_file = "./result.gpg";
    char *verify_file = "./result";
    size_t max_buflen = 2048, buflen;
    char *buf = malloc(max_buflen * sizeof(char));
    FILE *fh = NULL;

    err = gpgme_new (&ctx);
    if(err) return bang (err);

    gpgme_set_armor (ctx, 1);

    err = gpgme_get_key (ctx, fp, &recp[0], 0);
    if(err) return bang (err);

    err = gpgme_data_new_from_mem (&plain, plaintext, strlen(plaintext), 0);
    if(err) return bang (err);

    err = gpgme_data_new (&cipher);
    if(err) return bang (err);

    err = gpgme_op_encrypt (ctx, recp, flags, plain, cipher);
    if(err) return bang (err);

    gpgme_data_seek(cipher, 0, SEEK_SET);
    buflen = gpgme_data_read(cipher, buf, max_buflen);
    if (1 > buflen || buflen == max_buflen)
        return bang_ ("Failed to read ciphertext");

    fh = fopen(result_file, "w");
    if(!fh) bang_ ("failed to open result_file");

    fwrite(buf, sizeof(char), buflen, fh);
    fclose(fh);
    fh = NULL;

    memset(buf, 0, max_buflen);
    snprintf(buf, max_buflen-1, "gpg --output %s -d %s", verify_file, result_file);
    system(buf);

    memset(buf, 0, max_buflen);
    fh = fopen(verify_file, "rb");
    if(!fh) return bang_ ("failed to open verify_file");

    buflen = fread(buf, sizeof(char), max_buflen, fh);
    fclose(fh);

    if(buflen < 1 || buflen == max_buflen)
        return bang_ ("Failed to read result file");

    #ifdef INSERT_FAILURE
    buf[buflen-1] = '\0';
    #endif

    if (strncmp(buf, plaintext, strlen(plaintext)) != 0)
        return bang_ ("Decrypted text is different from original plaintext");

    return 0;
}
Example #20
0
int main()
{
   int fd;

   gpgme_ctx_t g_context;
   gpgme_engine_info_t enginfo;
   gpgme_data_t data;

   gpgme_error_t gerr;
   gpg_err_code_t gpg_err;

   gpgme_data_t g_plain;
   gpgme_data_t g_plain_recv;
   gpgme_data_t g_encrypt;
   gpgme_data_t g_encrypt_send;

   gpgme_key_t g_recipient[MAX_RCP+1];
   char *p;
   char b_encrypt[BIGBUF+1];

   char msg[EOF_L_MESSAGE];
   char msg_in[EOF_L_MESSAGE];

   int i, tmp;

   for(i=0;i<EOF_L_MESSAGE; i++) msg_in[i] = 0;
   for(i=0;i<EOF_L_MESSAGE; i++) msg[i] = 0;
   for(i=0;i<=BIGBUF; i++) b_encrypt[i] = 0;

   gpgme_check_version(NULL);

   gerr = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
   if(gerr != GPG_ERR_NO_ERROR) return 10;

   p = (char *) gpgme_get_protocol_name(GPGME_PROTOCOL_OpenPGP);
   printf("Version: %s\n",p);

   gerr = gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP, NULL, home);

   if(gerr == GPG_ERR_NO_ERROR) {
      printf("gpgme_set_engine_info: ok\n");
   } else {
      printf("gpgme_set_engine_info: err\n");
   }

   /* get engine information */
   gerr = gpgme_get_engine_info(&enginfo);
   if(gerr != GPG_ERR_NO_ERROR) return 3;

   printf("file=%s, home=%s\n",enginfo->file_name,enginfo->home_dir);

   /* create our own context */
   gerr = gpgme_new(&g_context);
   if(gerr != GPG_ERR_NO_ERROR) return 1;

   /* FIXME: both needed? */
   /* FIXME: why is the path (FILE_NAME) needed? */
   /* FIXME: /usr/bin/gpg must be changed to ~/.ceof/gpg/binary or similar */
   gerr = gpgme_ctx_set_engine_info (g_context, GPGME_PROTOCOL_OpenPGP,
               "/usr/bin/gpg",home);
   if(gerr != GPG_ERR_NO_ERROR) return 4;

   /* do not ascii armor data; use 1 for testing */
   //gpgme_set_armor(g_context, 0);
   gpgme_set_armor(g_context, 1);

   /* create buffers */
   gerr = gpgme_data_new(&data);
   if(gerr != GPG_ERR_NO_ERROR) return 12;

   gerr = gpgme_data_new(&g_plain_recv);
   if(gerr != GPG_ERR_NO_ERROR) return 20;

   gerr = gpgme_data_new(&g_encrypt);
   if(gerr != GPG_ERR_NO_ERROR) return 14;

   gerr = gpgme_data_new(&g_encrypt_send);
   if(gerr != GPG_ERR_NO_ERROR) return 24;

   /* fill buffers */
   /* gerr = gpgme_data_new(&g_plain);
   if(gerr != GPG_ERR_NO_ERROR) return 13;

   printf("strlen(%s) = %d\n",msg,i);
   i -= gpgme_data_write(g_plain, msg, i);
   if(i) {
      printf("size mismatch\n");
      return 12;
   } */
   strncpy(msg, "==> Erste Nachricht\n\n", EOF_L_MESSAGE);
   i = strlen(msg);
   gerr = gpgme_data_new_from_mem (&g_plain, msg, i, 0);


   /* setup recipient */
   gerr = gpgme_op_keylist_start(g_context, "nico schottelius", 0);
   if(gerr != GPG_ERR_NO_ERROR) return 11;

   i=0;
   gerr = gpgme_op_keylist_next(g_context, &g_recipient[0]);
   while((gpg_err = gpg_err_code(gerr)) != GPG_ERR_EOF) {
      /* for testing: one call of gpgme_op_keylist_next is enough */
      break;
      if(gerr == GPG_ERR_INV_VALUE) {
         printf("invalid pointer\n");
         return 15;
      } else if(gerr == GPG_ERR_ENOMEM) {
         printf("no mem\n");
         return 16;
      }

      printf ("%s: %s <%s> (%d)\n", g_recipient[0]->subkeys->keyid, g_recipient[0]->uids->name, g_recipient[0]->uids->email, i);
      i++;

      /* FIXME: this resets the good filled buffer ... */
      gerr = gpgme_op_keylist_next(g_context, &g_recipient[0]);
   }
   g_recipient[1] = NULL;

   /* all above seems to be wrong ... */
   gerr = gpgme_get_key(g_context,"775506B45998BF57D0D4AFF27C6E747C38616ADC", &g_recipient[0], 0);
   if(gerr != GPG_ERR_NO_ERROR) return 32;


   /* en/decrypt message */
   //gerr = gpgme_op_encrypt_sign(g_context, g_recipient, 0, g_plain, g_encrypt);
   gerr = gpgme_op_encrypt(g_context, g_recipient, 0, g_plain, g_encrypt);
   if(gerr != GPG_ERR_NO_ERROR) {
      printf("gerr=%d\n",gerr);
      return 18;
   }

   /* transfer the data into our own buffer,
    * so the data is saved; you cannot
    * reuse the gpgme buffers directly as in
    *    gerr = gpgme_op_decrypt(g_context, g_encrypt, g_plain_recv);
    *
    */
   i = gpgme_data_seek(g_encrypt, 0, SEEK_END);

   if(i > BIGBUF) return 22;
   printf("buflen: %d\n",i);
   
   /* reset to the beginning */
   gpgme_data_seek(g_encrypt, 0, SEEK_SET);

   if(gpgme_data_read(g_encrypt, b_encrypt, i) == -1) {
      perror("pgme_data_read");
      return 23;
   }
   printf("crypt:\n%s\n", b_encrypt);
   fd = open("testcrypt",O_RDWR|O_CREAT);
   if(fd == -1) return 40;
   if(write_all(fd, b_encrypt, BIGBUF) <= 0) return 41;
   close(fd);

   /* until here it works, testcrypt contains
    * data and can be decrypted ...
    *
    * perhaps the context needs some reset?
    */

   if((tmp = gpgme_data_write(g_encrypt_send, b_encrypt, i)) == -1) {
      perror("pgme_data_write");
      return 23;
   }
   printf("crypt-wrote:%d\n", tmp);

   /* look for contexts */

   gerr = gpgme_op_decrypt(g_context, g_encrypt_send, g_plain_recv);
   if(gerr != GPG_ERR_NO_ERROR) {
      printf("gerr=%d\n",gerr);
      return 19;
   }

   /* open communication channel: netcat */

   /* listen for input from:
    * stdin
    * communication channel
    */

   /* de/encode data from comm channel */

   return 1;
}
Example #21
0
int main(int argc, char *argv[])
{
	char * op=(char *)0;
	char * search=(char *)0;
	char * searchdec=(char *)0;
	char * exact=(char *)0;

	gpgme_ctx_t gpgctx;
	gpgme_key_t gpgkey;
	gpgme_error_t gpgerr;
	gpgme_engine_info_t enginfo;

	char * qstring, * pchar;

	pchar=getenv("QUERY_STRING");
	if (! pchar || *pchar == '\0' ) {
		http_header(500,CTYPE_HTML_STR);
		printf("<html><head><title>Error handling request</title></head><body><h1>Error handling request: there is no query string.</h1></body></html>");
		return 1;
	}
	qstring=strndup(pchar,QSTRING_MAX); /* copy the QUERY from env to write in */
	pchar=qstring;

	while (pchar && *pchar) {
		if (!strncmp(pchar,"op=",3)) {
			pchar+=3;
			op=pchar;
		} else if (!strncmp(pchar,"search=",7)) {
			pchar+=7;
			search=pchar;
		} else if (!strncmp(pchar,"options=",8)) {
			/*this parameter is useless now, as today we only support "mr" option and always enable it (machine readable) */
			pchar+=8;
			//options=pchar;
		} else if (!strncmp(pchar,"fingerprint=",12)) {
			/*this parameter is useless now as we only support "mr" options which don't care this */
			pchar+=12;
			//fingerprints=pchar;
		} else if (!strncmp(pchar,"exact=",6)) {
			pchar+=6;
			exact=pchar;
		} /*else: Other parameter not in hkp draft are quietly ignored */
		pchar=strchr(pchar,'&');
		if (pchar) {
			*pchar='\0';
			pchar++;
		}
	}

	if (exact) {
		if (!strcmp(exact,"off")) {
			exact=(char *) 0; /* off is default */
		} else if (!strcmp(exact,"on")) {
			http_header(501,CTYPE_HTML_STR);
			printf("<html><head><title>Not implemented</title></head><body><h1>Error handling request: \"exact\" parameter is not implemented.</h1></body></html>");
			return 1;
		} else {
			http_header(500,CTYPE_HTML_STR);
			printf("<html><head><title>Error handling request</title></head><body><h1>Error handling request: \"exact\" parameter only take \"on\" or \"off\" as argument.</h1></body></html>");
			return 1;
		}
	}

	if ( ! search ) { 
		/* (mandatory parameter) */
		http_header(500,CTYPE_HTML_STR);
		printf("<html><head><title>Error handling request</title></head><body><h1>Error handling request: Missing \"search\" parameter in \"%s\".</h1></body></html>",getenv("QUERY_STRING"));
		return 1;
	} else {
		if (searchdec=malloc(strlen(search)*sizeof(char)+1)) 
			strdecode(searchdec,search);
		else {
			http_header(500,CTYPE_HTML_STR);
			printf("<html><head><title>Internal Error</title></head><body><h1>Internal malloc(%d) for search fail.</h1></body></html>",strlen(search)*sizeof(char)+1);
			return 1;
		}
	}

	if ( ! op )
		op="index"; /* defaut operation */

	/* Check gpgme version ( http://www.gnupg.org/documentation/manuals/gpgme/Library-Version-Check.html )*/
	setlocale (LC_ALL, "");
	gpgme_check_version (NULL);
	gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
	/* check for OpenPGP support */
	gpgerr=gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
	if ( gpgerr  != GPG_ERR_NO_ERROR ) {
		http_header(500,CTYPE_HTML_STR);
		printf("<html><head><title>Internal Error</title></head><body><h1>Error handling request due to internal error (gpgme_engine_check_version).</h1></body></html>");
		return 1;
	}

	/* create context */
	gpgerr=gpgme_new(&gpgctx);
	if ( gpgerr  != GPG_ERR_NO_ERROR ) {
		http_header(500,CTYPE_HTML_STR);
		printf("<html><head><title>Internal Error</title></head><body><h1>Error handling request due to internal error (gpgme_new %d).</h1></body></html>",gpgerr);
		return 1;
	}
	/*gpgerr = gpgme_get_engine_info(&enginfo);
	gpgerr |= gpgme_ctx_set_engine_info(gpgctx, GPGME_PROTOCOL_OpenPGP, enginfo->file_name,"../../new");
	if ( gpgerr  != GPG_ERR_NO_ERROR ) {
		http_header(500,CTYPE_HTML_STR);
		printf("<html><head><title>Internal Error</title></head><body><h1>Error handling request due to internal error (gpgme_ctx_set_engine_info %d).</h1></body></html>",gpgerr);
		return 1;
	}*/

	if (!strcmp(op, "get")) {
		gpgme_data_t gpgdata;
		char buff[BUFFSIZE];
		ssize_t read_bytes;

		gpgme_set_armor(gpgctx,1);
		gpgerr = gpgme_data_new(&gpgdata);
		if (gpgerr == GPG_ERR_NO_ERROR) {
			gpgerr = gpgme_data_set_encoding(gpgdata,GPGME_DATA_ENCODING_ARMOR);
			if (gpgerr == GPG_ERR_NO_ERROR)
				gpgerr = gpgme_op_export(gpgctx,searchdec,0,gpgdata);
		}

		if ( gpgerr != GPG_ERR_NO_ERROR) {
			http_header(500,CTYPE_HTML_STR);
			printf("<html><head><title>Internal Error</title></head><body><h1>Error handling request due to internal error (%d).</h1></body></html>",gpgerr);
			return 1;
		}
		gpgme_data_seek (gpgdata, 0, SEEK_SET);
		read_bytes = gpgme_data_read (gpgdata, buff, BUFFSIZE);
		if ( read_bytes == -1 ) {
			http_header(500,CTYPE_HTML_STR);
			printf("<html><head><title>Internal Error</title></head><body><h1>Error handling request due to internal error (%s).</h1></body></html>",gpgme_strerror(errno));
			return 1;
		} else if ( read_bytes <= 0 ) {
			http_header(404,CTYPE_HTML_STR);
			printf("<html><head><title>ludd Public Key Server -- Get: %s</title></head><body><h1>Public Key Server -- Get: %s : No key found ! :-( </h1></body></html>",search,search);
			return 0;
		} else {
			http_header(200,CTYPE_HTML_STR);
			printf("<html><head><title>ludd Public Key Server -- Get: %s</title></head><body><h1>Public Key Server -- Get: %s</h1><pre>",search,search);
			fwrite(buff, sizeof(char),read_bytes,stdout); /* Now it's too late to test fwrite return value ;-) */ 
			while ( (read_bytes = gpgme_data_read (gpgdata, buff, BUFFSIZE)) > 0 )
				fwrite(buff, sizeof(char),read_bytes,stdout);
			printf("\n</pre></body></html>");
			return 0;
		}

	} else if (!strcmp(op, "index")) {
		char uidenc[BUFFSIZE];
		char begin=0;
		gpgme_user_id_t gpguid;

		/* check for the searched key(s) */
		gpgerr = gpgme_op_keylist_start(gpgctx, searchdec, 0);
		//gpgerr = gpgme_op_keylist_start(gpgctx, NULL, 0);
		if ( gpgerr  != GPG_ERR_NO_ERROR ) {
			http_header(500,CTYPE_HTML_STR);
			printf("<html><head><title>Internal Error</title></head><body><h1>Error handling request due to internal error (gpgme_op_keylist_start %d).</h1></body></html>",gpgerr);
			return 1;
		}

		gpgerr = gpgme_op_keylist_next (gpgctx, &gpgkey);
		while (gpgerr == GPG_ERR_NO_ERROR) {
			if (!begin) {
				http_header(200,"text/plain; charset=utf-8");
				begin=1;
				/* Luckily: info "header" is optionnal, see draft-shaw-openpgp-hkp-00.txt */
			}
			/* first subkey is the main key */
			printf("pub:%s:%d:%d:%d:%d\n",gpgkey->subkeys->fpr,gpgkey->subkeys->pubkey_algo,gpgkey->subkeys->length,gpgkey->subkeys->timestamp,(gpgkey->subkeys->expires?gpgkey->subkeys->expires:-1));
			gpguid=gpgkey->uids;
			while (gpguid) {
				printf("uid:%s (%s) <%s>:\n",gpguid->name,gpguid->comment,gpguid->email);
				gpguid=gpguid->next;
			}
			gpgme_key_unref(gpgkey);
			gpgerr = gpgme_op_keylist_next (gpgctx, &gpgkey);
		}
			gpgme_key_unref(gpgkey); /* ... because i don't know how "gpgme_op_keylist_next" behave when not returning GPG_ERR_NO_ERROR */
		if (!begin) {
			http_header(404,CTYPE_HTML_STR);
			printf("<html><head><title>ludd Public Key Server -- index: %s</title></head><body><h1>index Error: No keys found</h1></body></html>",search);
			return 1;
		}
		return 0;

	} else if ( !strcmp(op, "photo") || !strcmp(op, "x-photo") ) {
			http_header(501,CTYPE_HTML_STR);
			printf("<html><head><title>Not implemented</title></head><body><h1>Error handling request: \"%s\" operation is not implemented.</h1></body></html>",op);
			return 1;
	} else {
		http_header(500,CTYPE_HTML_STR);
		printf("<html><head><title>Error handling request</title></head><body><h1>Error handling request: Unrecognized action in \"%s\".</h1></body></html>",getenv("QUERY_STRING"));
		return 1;
	}
}
Example #22
0
gpointer
sign_file (const gchar *input_file_path, const gchar *fpr)
{
    gpgme_error_t error;
    gpgme_ctx_t context;
    gpgme_key_t signing_key;
    gpgme_data_t clear_text, signed_text;
    gpgme_sign_result_t result;
    gchar *buffer;
    gssize nbytes;

    error = gpgme_new (&context);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        return GPGME_ERROR;
    }

    gpgme_set_armor (context, 0);

    error = gpgme_engine_check_version (GPGME_PROTOCOL_OpenPGP);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        gpgme_release (context);
        return GPGME_ERROR;
    }

    const char *keyring_dir = gpgme_get_dirinfo ("homedir");
    error = gpgme_ctx_set_engine_info (context, GPGME_PROTOCOL_OpenPGP, NULL, keyring_dir);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        gpgme_release (context);
        return GPGME_ERROR;
    }

    error = gpgme_get_key (context, fpr, &signing_key, 1);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        gpgme_release (context);
        return GPGME_ERROR;
    }

    error = gpgme_signers_add (context, signing_key);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        cleanup (NULL, NULL, NULL, NULL, &signing_key, &context);
        return GPGME_ERROR;
    }

    FILE *infp = g_fopen (input_file_path, "r");
    if (infp == NULL) {
        g_printerr ("Couldn't open input file\n");
        cleanup (NULL, NULL, NULL, NULL, &signing_key, &context);
        return FILE_OPEN_ERROR;
    }

    error = gpgme_data_new_from_stream (&clear_text, infp);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        cleanup (infp, NULL, NULL, NULL, &signing_key, &context);
        return GPGME_ERROR;
    }

    error = gpgme_data_new (&signed_text);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        cleanup (infp, NULL, NULL, NULL, &signing_key, &context);
        return GPGME_ERROR;
    }

    error = gpgme_op_sign (context, clear_text, signed_text, GPGME_SIG_MODE_DETACH);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        cleanup (infp, NULL, NULL, NULL, &signing_key, &context);
        return GPGME_ERROR;
    }

    result = gpgme_op_sign_result (context);
    if (result->invalid_signers) {
        g_printerr ("Invalid signer found: %s\n", result->invalid_signers->fpr);
        cleanup (infp, NULL, NULL, NULL, &signing_key, &context);
        return GPGME_ERROR;
    }
    if (!result->signatures || result->signatures->next) {
        g_printerr ("Unexpected number of signatures created\n");
        cleanup (infp, NULL, NULL, NULL, &signing_key, &context);
        return GPGME_ERROR;
    }

    error = gpgme_data_seek (signed_text, 0, SEEK_SET);
    if (error) {
        g_printerr ("%s:%d: %s: %s\n", __FILE__, __LINE__, gpgme_strsource (error), gpgme_strerror (error));
        cleanup (infp, NULL, NULL, NULL, &signing_key, &context);
        return GPGME_ERROR;
    }

    buffer = g_try_malloc0 (SIG_MAXLEN);
    if (buffer == NULL) {
        g_printerr ("Couldn't allocate memory\n");
        cleanup (infp, NULL, NULL, NULL, &signing_key, &context);
        return MEMORY_ALLOCATION_ERROR;
    }

    nbytes = gpgme_data_read (signed_text, buffer, SIG_MAXLEN);
    if (nbytes == -1) {
        g_printerr ("Error while reading data\n");
        cleanup (infp, NULL, NULL, NULL, &signing_key, &context);
        return GPGME_ERROR;
    }

    GError *gerr = NULL;
    gchar *output_file_path = g_strconcat (input_file_path, ".sig", NULL);
    GFile *fpout = g_file_new_for_path (output_file_path);
    GFileOutputStream *ostream = g_file_append_to (fpout, G_FILE_CREATE_REPLACE_DESTINATION, NULL, &gerr);
    if (gerr != NULL) {
        g_printerr ("Couldn't open output file for writing\n");
        cleanup (infp, fpout, NULL, output_file_path, &signing_key, &context);
        return FILE_OPEN_ERROR;
    }

    gssize wbytes = g_output_stream_write (G_OUTPUT_STREAM (ostream), buffer, nbytes, NULL, &gerr);
    if (wbytes == -1) {
        g_printerr ("Couldn't write the request number of bytes (%s)\n", gerr->message);
        cleanup (infp, fpout, ostream, output_file_path, &signing_key, &context);
        return FILE_WRITE_ERROR;
    }

    cleanup (infp, fpout, ostream, output_file_path, &signing_key, &context);

    return SIGN_OK;
}
Example #23
0
static gpgme_error_t
gpgconf_write (void *engine, char *arg1, char *arg2, gpgme_data_t conf)
{
  struct engine_gpgconf *gpgconf = engine;
  gpgme_error_t err = 0;
#define BUFLEN 1024
  char buf[BUFLEN];
  int buflen = 0;
  char *argv[] = { NULL /* file_name */, arg1, arg2, 0 };
  int rp[2];
  struct spawn_fd_item_s cfd[] = { {-1, 0 /* STDIN_FILENO */}, {-1, -1} };
  int status;
  int nwrite;

  /* FIXME: Deal with engine->home_dir.  */

  /* _gpgme_engine_new guarantees that this is not NULL.  */
  argv[0] = gpgconf->file_name;

  if (_gpgme_io_pipe (rp, 0) < 0)
    return gpg_error_from_syserror ();

  cfd[0].fd = rp[0];

  status = _gpgme_io_spawn (gpgconf->file_name, argv, 0, cfd, NULL, NULL, NULL);
  if (status < 0)
    {
      _gpgme_io_close (rp[0]);
      _gpgme_io_close (rp[1]);
      return gpg_error_from_syserror ();
    }

  for (;;)
    {
      if (buflen == 0)
	{
	  do
	    {
	      buflen = gpgme_data_read (conf, buf, BUFLEN);
	    }
	  while (buflen < 0 && errno == EAGAIN);

	  if (buflen < 0)
	    {
	      err = gpg_error_from_syserror ();
	      _gpgme_io_close (rp[1]);
	      return err;
	    }
	  else if (buflen == 0)
	    {
	      /* All is written.  */
	      _gpgme_io_close (rp[1]);
	      return 0;
	    }
	}

      do
	{
	  nwrite = _gpgme_io_write (rp[1], buf, buflen);
	}
      while (nwrite < 0 && errno == EAGAIN);

      if (nwrite > 0)
	{
	  buflen -= nwrite;
	  if (buflen > 0)
	    memmove (&buf[0], &buf[nwrite], buflen);
	}
      else if (nwrite < 0)
	{
	  _gpgme_io_close (rp[1]);
	  return gpg_error_from_syserror ();
	}
    }

  return 0;
}
QString QalfCrypto::sign(QString &message, QString &key) {
	gpgme_key_t gpgkey ;
	gpgme_data_t signature ;
	gpgme_data_t msg ;
	gpgme_verify_result_t verification ;
	gpgme_signature_t signatures ;
 	gpgme_error_t result  ;
	char  * buffer ;
		
	gpgme_set_passphrase_cb(context,&passphrase_callback,NULL) ;
	result = gpgme_set_protocol(context,GPGME_PROTOCOL_OpenPGP) ;
	Q_ASSERT(gpgme_err_code(result) == GPG_ERR_NO_ERROR) ;
	gpgme_set_armor(context,1) ;
	gpgme_set_textmode(context,1) ;

	gpgme_signers_clear(context) ;
	result = gpgme_set_keylist_mode(context,GPGME_KEYLIST_MODE_LOCAL) ;

	// retrieving key
	result = gpgme_get_key(context, key.toAscii().data(),&gpgkey,1) ;
	Q_ASSERT(result == GPG_ERR_NO_ERROR) ;
	Q_ASSERT(gpgkey != 0) ;

	// signing
	result = gpgme_signers_add(context,gpgkey) ;
	Q_ASSERT(result == GPG_ERR_NO_ERROR) ;
	
	result = gpgme_data_new(&signature);
	Q_ASSERT(result == GPG_ERR_NO_ERROR) ;

	int message_length = message.toAscii().size() ;
	char * message_char = (char *) calloc(message_length+1,sizeof(char)) ;
	memcpy(message_char,message.toAscii().data(),message_length) ;
// 	printf("memcmp : %d\n",memcmp(message_char,"1fc36e1d41a93c1d79f6872198f426129320d287",message_length+1)) ;
	result = gpgme_data_new_from_mem(&msg,message_char,message_length,0) ;
	
	gpgme_data_seek(signature,0,SEEK_SET) ;
	gpgme_data_seek(msg,0,SEEK_SET) ;
	
	result = gpgme_op_sign(context, msg,signature, GPGME_SIG_MODE_DETACH) ;
	Q_ASSERT(gpgme_err_code(result) == GPG_ERR_NO_ERROR || gpgme_err_code(result) == GPG_ERR_BAD_PASSPHRASE || gpgme_err_code(result) == GPG_ERR_CANCELED) ;
	
// 	gpgme_data_seek(signature,0,SEEK_SET) ;
// 	gpgme_data_seek(msg,0,SEEK_SET) ;
// 	
// 	result = gpgme_op_verify (context, signature, msg , 0) ;
// 	Q_ASSERT(gpgme_err_code(result) != GPG_ERR_INV_VALUE) ;
// 	Q_ASSERT(gpgme_err_code(result) != GPG_ERR_NO_DATA) ;
// 	Q_ASSERT(result == GPG_ERR_NO_ERROR) ;
// 	
// 	verification = gpgme_op_verify_result(context) ;
// 	Q_ASSERT(verification != 0) ;
// 	
// 	signatures = verification->signatures ;
// 	Q_ASSERT(verification->signatures != 0) ;
// 	result = signatures->status ;
// 	printf("status : %d\n",gpgme_err_code(result)) ;
// 	printf("signature summary : %d\n",signatures->summary) ;
// 	Q_ASSERT(signatures->summary == GPGME_SIGSUM_VALID | GPGME_SIGSUM_GREEN) ;
// 	
	QString signatureStr ;
	buffer = (char *) calloc(2048,sizeof(char)) ;
	gpgme_data_seek(signature,0,SEEK_SET) ;
	gpgme_data_read(signature,buffer,2048) ;

	signatureStr += buffer ;

	qDebug() << "signature" << signatureStr ;
	
	gpgme_data_release(signature) ;
	gpgme_key_unref(gpgkey) ;
	gpgme_data_release(msg) ;
	return signatureStr ;
}