Friend Code

From Custom Mario Kart
Revision as of 22:34, 4 March 2014 by Chadderz (talk | contribs) (→‎Player ID to Friend Code conversion: To be clear, it's a digest of 8 bytes,)
Jump to navigation Jump to search

Many Wii games including Mario Kart Wii use friend codes as unique id to connect to other players.

In Mario Kart Wii (and probably in all other Wii games) the friend code is stored as a 64 bit number. It is displayed as a 12 digit decimal number separated by minus signs after the fourth and eighth digit: 1234-5678-9012.

The maximum number is 9999-9999-9999, or in hex, E8.D4A5.0FFF. This makes clear, that the first 3 bytes of a 64 bit friend code are always zero and that are only 40 bits are used. After checking more than 350 friend codes, probably only 39 bits are used and the maximum number is 5497-5581-3887, or in hex, 7F.FFFF.FFFF.

An interesting aspect is, that the MKWii Network Protocol uses only the lowest 32 bits to identify the different users (User-ID, that is also used for identification). Bits 32..39 are a checksum or a randomly generated number.

Example:

  1. Assume, that your friend code is: 1234-5678-9012.
  2. The hex value is: 1C.BE99.1A14
  3. Only the least significant 32 bits are relevant: BE99.1A14 (hex)
  4. In database queries you will see the decimal presentation of this 32-bit number: 3197704724

Player ID to Friend Code conversion

u64 pid_to_fc(u32 pid) {
  if (pid == 0)
    // behaviour observed in MKWii, more likely an error condition
    return 0;
  else {
    u8 buffer[8], md5[8];
    // buffer is pid in little endian, followed by RMCJ in little endian
    buffer[0] = pid >> 0;
    buffer[1] = pid >> 8;
    buffer[2] = pid >> 16;
    buffer[3] = pid >> 24;
    buffer[4] = 'J';
    buffer[5] = 'C';
    buffer[6] = 'M';
    buffer[7] = 'R';
    // md5digest computes the digest of the second parameter and stores it in the first.
    md5digest(md5, buffer, 8);
    return ((u64)md5[0] << 31) | pid;
  }
}