Skip to content

Instantly share code, notes, and snippets.

@bettse
Created November 30, 2023 05:16
Show Gist options
  • Save bettse/a3ce6b4f728586fd045ecffdc4441132 to your computer and use it in GitHub Desktop.
Save bettse/a3ce6b4f728586fd045ecffdc4441132 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#if defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#define bswap_16(x) OSSwapInt16(x)
#define bswap_32(x) OSSwapInt32(x)
#define bswap_64(x) OSSwapInt64(x)
#else
#include <byteswap.h>
#endif
#define HEX 0x10
#define UID_LEN 4
#define SECTOR_COUNT 16
#define KEY_MASK 0xFFFFFFFFFFFF
#define POLY UINT64_C(0x42f0e1eba9ea3693)
#define TOP UINT64_C(0x800000000000)
uint64_t crc64_like(uint64_t result, uint8_t sector) {
result ^= (uint64_t)sector << 40;
for(int i = 0; i < 8; i++) {
result = (result & TOP) ? (result << 1) ^ POLY : result << 1;
}
return result;
}
uint64_t taghash(uint32_t uid) {
uint64_t result = 0x9AE903260CC4;
uint8_t uidBytes[UID_LEN] = {0};
memcpy(uidBytes, &uid, UID_LEN);
for(int i = 0; i < UID_LEN; i++) {
result = crc64_like(result, uidBytes[i]);
}
return result;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("%s <4 byte uid in hex>\n", argv[0]);
return 1;
}
uint32_t uid = strtoul(argv[1], NULL, HEX);
printf("uid = %08x\n", uid);
printf("Sector 0: 4b0b20107ccb\n"); //Fixed sector 0 key
uid = bswap_32(uid);
uint64_t hash = taghash(uid);
for(uint8_t sector = 1; sector < SECTOR_COUNT; sector++) {
uint64_t sectorhash = crc64_like(hash, sector);
uint64_t key = bswap_64(sectorhash & KEY_MASK) >> 16;
printf("Sector %u: %012" PRIx64 "\n", sector, key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment