For a V3 key, the eight-octet Key ID consists of the low 64 bits of the public modulus of the RSA key.¶

The fingerprint of a V3 key is formed by hashing the body (but not the two-octet length) of the MPIs that form the key material (public modulus n, followed by exponent e) with MD5.
Note that both V3 keys and MD5 are deprecated.¶

A V4 fingerprint is the 160-bit SHA-1 hash of the octet 0x99, followed by the two-octet packet length, followed by the entire Public-Key packet starting with the version field.
The Key ID is the low-order 64 bits of the fingerprint.
Here are the fields of the hash material, with the example of a DSA key:¶

a.1) 0x99 (1 octet)¶

a.2) two-octet scalar octet count of (b)-(e)¶

b) version number = 4 (1 octet);¶

c) timestamp of key creation (4 octets);¶

d) algorithm (1 octet): 17 = DSA (example);¶

e) Algorithm-specific fields.¶

Algorithm-Specific Fields for DSA keys (example):¶

e.1) MPI of DSA prime p;¶

e.2) MPI of DSA group order q (q is a prime divisor of p-1);¶

e.3) MPI of DSA group generator g;¶

e.4) MPI of DSA public-key value y (= g**x mod p where x is secret).¶

A V5 fingerprint is the 256-bit SHA2-256 hash of the octet 0x9A, followed by the four-octet packet length, followed by the entire Public-Key packet starting with the version field.
The Key ID is the high-order 64 bits of the fingerprint.
Here are the fields of the hash material, with the example of a DSA key:¶

a.1) 0x9A (1 octet)¶

a.2) four-octet scalar octet count of (b)-(f)¶

b) version number = 5 (1 octet);¶

c) timestamp of key creation (4 octets);¶

d) algorithm (1 octet): 17 = DSA (example);¶

e) four-octet scalar octet count for the following key material;¶

f) algorithm-specific fields.¶

Algorithm-Specific Fields for DSA keys (example):¶

f.1) MPI of DSA prime p;¶

f.2) MPI of DSA group order q (q is a prime divisor of p-1);¶

f.3) MPI of DSA group generator g;¶

f.4) MPI of DSA public-key value y (= g**x mod p where x is secret).¶

Note that it is possible for there to be collisions of Key IDs -- two different keys with the same Key ID.
Note that there is a much smaller, but still non-zero, probability that two different keys have the same fingerprint.¶

Also note that if V3, V4, and V5 format keys share the same RSA key material, they will have different Key IDs as well as different fingerprints.¶

Finally, the Key ID and fingerprint of a subkey are calculated in the same way as for a primary key, including the 0x99 (V3 and V4 key) or 0x9A (V5 key) as the first octet (even though this is not a valid packet ID for a public subkey).¶