summaryrefslogtreecommitdiffstats
path: root/ffi/examples/armor.c
blob: a2643667453d3ac0a029cbb38a9a54a05acbbcd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#define _GNU_SOURCE
#include <assert.h>
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sequoia.h>

const char *armored =
  "-----BEGIN PGP ARMORED FILE-----\n"
  "Key0: Value0\n"
  "Key1: Value1\n"
  "\n"
  "SGVsbG8gd29ybGQh\n"
  "=s4Gu\n"
  "-----END PGP ARMORED FILE-----\n";

int
main (int argc, char **argv)
{
  sq_error_t err;
  sq_context_t ctx;
  sq_reader_t bytes;
  sq_reader_t armor;
  sq_armor_kind_t kind;
  char message[12];
  sq_armor_header_t *header;
  size_t header_len;

  ctx = sq_context_new ("org.sequoia-pgp.example", &err);
  if (ctx == NULL)
    error (1, 0, "Initializing sequoia failed: %s",
           sq_error_string (err));

  bytes = sq_reader_from_bytes ((uint8_t *) armored, strlen (armored));
  armor = sq_armor_reader_new (bytes, SQ_ARMOR_KIND_ANY);

  header = sq_armor_reader_headers (ctx, armor, &header_len);
  if (header == NULL)
    error (1, 0, "Getting headers failed: %s",
           sq_error_string (err));

  assert (header_len == 2);
  assert (strcmp (header[0].key, "Key0") == 0
          && strcmp (header[0].value, "Value0") == 0);
  assert (strcmp (header[1].key, "Key1") == 0
          && strcmp (header[1].value, "Value1") == 0);
  for (size_t i = 0; i < header_len; i++)
    {
      free (header[i].key);
      free (header[i].value);
    }
  free (header);

  kind = sq_armor_reader_kind (armor);
  assert (kind == SQ_ARMOR_KIND_FILE);

  if (sq_reader_read (ctx, armor, (uint8_t *) message, 12) < 0)
    {
      err = sq_context_last_error (ctx);
      error (1, 0, "Reading failed: %s",
	     sq_error_string (err));
    }

  assert (memcmp (message, "Hello world!", 12) == 0);

  sq_reader_free (armor);
  sq_reader_free (bytes);
  sq_context_free (ctx);
  return 0;
}