aboutsummaryrefslogtreecommitdiffstats
path: root/src/m_paper_key/extract.cpp
blob: 1f0994acf5e15ffa4ba3b2beadbc965758dea2ea (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
 * Copyright (C) 2007, 2017 David Shaw <[email protected]>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 */

#include "extract.h"

#include <cstdio>

#include "output.h"
#include "packets.h"
#include "parse.h"

extern int verbose;

int extract(FILE *input, FILE *output, enum data_type output_type) {
  struct packet *packet;
  int offset;
  unsigned char fingerprint[20];
  unsigned char version = 0;

  packet = parse(input, 5, 0);
  if (!packet) {
    fprintf(stderr, "Unable to find secret key packet\n");
    return 1;
  }

  offset = extract_secrets(packet);
  if (offset == -1) return 1;

  if (verbose > 1) fprintf(stderr, "Secret offset is %d\n", offset);

  calculate_fingerprint(packet, offset, fingerprint);

  if (verbose) {
    fprintf(stderr, "Primary key fingerprint: ");
    print_bytes(stderr, fingerprint, 20);
    fprintf(stderr, "\n");
  }

  output_start(output, output_type, fingerprint);
  output_bytes(&version, 1);
  output_bytes(packet->buf, 1);
  output_bytes(fingerprint, 20);
  output_length16(packet->len - offset);
  output_bytes(&packet->buf[offset], packet->len - offset);

  free_packet(packet);

  while ((packet = parse(input, 7, 5))) {
    offset = extract_secrets(packet);
    if (offset == -1) return 1;

    if (verbose > 1) fprintf(stderr, "Secret subkey offset is %d\n", offset);

    calculate_fingerprint(packet, offset, fingerprint);

    if (verbose) {
      fprintf(stderr, "Subkey fingerprint: ");
      print_bytes(stderr, fingerprint, 20);
      fprintf(stderr, "\n");
    }

    output_bytes(packet->buf, 1);
    output_bytes(fingerprint, 20);
    output_length16(packet->len - offset);
    output_bytes(&packet->buf[offset], packet->len - offset);

    free_packet(packet);
  }

  output_finish();
  output_end();

  if (input == stdin) {
    /* Consume everything else on input */
    while ((fgetc(input) != EOF));
  }

  return 0;
}