keygen.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. size_t strLen = strlen((char*)baseKeys->typeString);
  21. size_t typeStringSize = sizeof(baseKeys->typeString);
  22. output = (uint8_t*)strncpy((char*)output, baseKeys->typeString, typeStringSize);
  23. output += strLen + 1;
  24. // 2: Append (16 - magicBytesSize) from the input seed
  25. size_t leadingSeedBytes = 16 - baseKeys->magicBytesSize;
  26. memcpy(output, baseSeed, leadingSeedBytes);
  27. output += leadingSeedBytes;
  28. // 3: Append all bytes from magicBytes
  29. memcpy(output, baseKeys->magicBytes, baseKeys->magicBytesSize);
  30. output += baseKeys->magicBytesSize;
  31. // 4: Append bytes 0x10-0x1F from input seed
  32. memcpy(output, baseSeed + 0x10, 16);
  33. output += 16;
  34. // 5: Xor last bytes 0x20-0x3F of input seed with AES XOR pad and append them
  35. unsigned int i;
  36. for (i = 0; i < 32; i++) {
  37. output[i] = baseSeed[i + 32] ^ baseKeys->xorPad[i];
  38. }
  39. output += 32;
  40. *outputSize = output - start;
  41. }
  42. void nfc3d_keygen(const nfc3d_keygen_masterkeys * baseKeys, const uint8_t * baseSeed, nfc3d_keygen_derivedkeys * derivedKeys) {
  43. uint8_t preparedSeed[NFC3D_DRBG_MAX_SEED_SIZE];
  44. size_t preparedSeedSize;
  45. nfc3d_keygen_prepare_seed(baseKeys, baseSeed, preparedSeed, &preparedSeedSize);
  46. nfc3d_drbg_generate_bytes(baseKeys->hmacKey, sizeof(baseKeys->hmacKey), preparedSeed, preparedSeedSize, (uint8_t *) derivedKeys, sizeof(*derivedKeys));
  47. }