2 * keyid.c - Routines to calculate key IDs.
4 * Jonathan McDowell <noodles@earth.li>
6 * Copyright 2002 Project Purple
8 * $Id: keyid.c,v 1.10 2004/05/31 22:04:51 noodles Exp $
11 #include <sys/types.h>
15 #include "keystructs.h"
22 * get_keyid - Given a public key returns the keyid.
23 * @publickey: The key to calculate the id for.
25 uint64_t get_keyid(struct openpgp_publickey *publickey)
27 return (get_packetid(publickey->publickey));
31 * get_fingerprint - Given a public key returns the fingerprint.
32 * @publickey: The key to calculate the id for.
33 * @fingerprint: The fingerprint (must be at least 20 bytes of space).
34 * @len: The length of the returned fingerprint.
36 * This function returns the fingerprint for a given public key. As Type 3
37 * fingerprints are 16 bytes and Type 4 are 20 the len field indicates
38 * which we've returned.
40 unsigned char *get_fingerprint(struct openpgp_packet *packet,
41 unsigned char *fingerprint,
45 struct md5_ctx md5_context;
47 size_t modlen, explen;
49 assert(fingerprint != NULL);
54 switch (packet->data[0]) {
57 md5_init_ctx(&md5_context);
60 * MD5 the modulus and exponent.
62 modlen = ((packet->data[8] << 8) +
63 packet->data[9] + 7) >> 3;
64 md5_process_bytes(&packet->data[10], modlen, &md5_context);
66 explen = ((packet->data[10+modlen] << 8) +
67 packet->data[11+modlen] + 7) >> 3;
68 md5_process_bytes(&packet->data[12 + modlen], explen,
71 md5_finish_ctx(&md5_context, fingerprint);
79 * TODO: Can this be 0x99? Are all public key packets old
80 * format with 2 bytes of length data?
83 SHA1Update(&sha_ctx, &c, sizeof(c));
84 c = packet->length >> 8;
85 SHA1Update(&sha_ctx, &c, sizeof(c));
86 c = packet->length & 0xFF;
87 SHA1Update(&sha_ctx, &c, sizeof(c));
88 SHA1Update(&sha_ctx, packet->data,
90 SHA1Final(fingerprint, &sha_ctx);
95 logthing(LOGTHING_ERROR, "Unknown key type: %d",
104 * get_packetid - Given a PGP packet returns the keyid.
105 * @packet: The packet to calculate the id for.
107 uint64_t get_packetid(struct openpgp_packet *packet)
113 unsigned char buff[20];
115 assert(packet != NULL);
117 switch (packet->data[0]) {
121 * For a type 2 or 3 key the keyid is the last 64 bits of the
122 * public modulus n, which is stored as an MPI from offset 8
125 offset = (packet->data[8] << 8) +
127 offset = ((offset + 7) / 8) + 2;
129 for (keyid = 0, i = 0; i < 8; i++) {
131 keyid += packet->data[offset++];
134 * Check for an RSA key; if not then log but accept anyway.
136 * 2 == RSA Encrypt-Only
139 if (packet->data[7] < 1 || packet->data[7] > 3) {
140 logthing(LOGTHING_NOTICE,
141 "Type 2 or 3 key, but not RSA: %llx (type %d)",
147 get_fingerprint(packet, buff, &length);
149 for (keyid = 0, i = 12; i < 20; i++) {
156 logthing(LOGTHING_ERROR, "Unknown key type: %d",