keygen.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * (c) 2015-2017 Marcos Del Sol Vives
  3. *
  4. * SPDX-License-Identifier: MIT
  5. */
  6. #include "drbg.h"
  7. #include "keygen.h"
  8. #include "util.h"
  9. #include <assert.h>
  10. #include <stdio.h>
  11. #include <string.h>
  12. void nfc3d_keygen_prepare_seed(const nfc3d_keygen_masterkeys * baseKeys, const uint8_t * baseSeed, uint8_t * output, size_t * outputSize) {
  13. assert(baseKeys != NULL);
  14. assert(baseSeed != NULL);
  15. assert(output != NULL);
  16. assert(outputSize != NULL);
  17. uint8_t * start = output;
  18. // 1: Copy whole type string
  19. output = memccpy(output, baseKeys->typeString, '\0', sizeof(baseKeys->typeString));
  20. // 2: Append (16 - magicBytesSize) from the input seed
  21. size_t leadingSeedBytes = 16 - baseKeys->magicBytesSize;
  22. memcpy(output, baseSeed, leadingSeedBytes);
  23. output += leadingSeedBytes;
  24. // 3: Append all bytes from magicBytes
  25. memcpy(output, baseKeys->magicBytes, baseKeys->magicBytesSize);
  26. output += baseKeys->magicBytesSize;
  27. // 4: Append bytes 0x10-0x1F from input seed
  28. memcpy(output, baseSeed + 0x10, 16);
  29. output += 16;
  30. // 5: Xor last bytes 0x20-0x3F of input seed with AES XOR pad and append them
  31. unsigned int i;
  32. for (i = 0; i < 32; i++) {
  33. output[i] = baseSeed[i + 32] ^ baseKeys->xorPad[i];
  34. }
  35. output += 32;
  36. *outputSize = output - start;
  37. }
  38. void nfc3d_keygen(const nfc3d_keygen_masterkeys * baseKeys, const uint8_t * baseSeed, nfc3d_keygen_derivedkeys * derivedKeys) {
  39. uint8_t preparedSeed[NFC3D_DRBG_MAX_SEED_SIZE];
  40. size_t preparedSeedSize;
  41. nfc3d_keygen_prepare_seed(baseKeys, baseSeed, preparedSeed, &preparedSeedSize);
  42. nfc3d_drbg_generate_bytes(baseKeys->hmacKey, sizeof(baseKeys->hmacKey), preparedSeed, preparedSeedSize, (uint8_t *) derivedKeys, sizeof(*derivedKeys));
  43. }