getkey.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #define _XOPEN_SOURCE 700
  2. #include <dirent.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include "deonebook.h"
  8. unsigned char *getkey(const char *keystring, const char *device)
  9. {
  10. if (keystring) {
  11. static unsigned char key[KEY_SIZE] = "";
  12. if (strlen(keystring) != (KEY_SIZE * 2)) {
  13. fprintf(stderr, "key must be %d hex characters\n", KEY_SIZE * 2);
  14. return NULL;
  15. }
  16. for (size_t i = 0; i < sizeof(key); i++) {
  17. char hex[] = { keystring[i * 2], keystring[i * 2 + 1], '\0' };
  18. key[i] = (unsigned char)strtoul(hex, NULL, 16);
  19. }
  20. return key;
  21. }
  22. if (!device) {
  23. device = "mmcblk0";
  24. } else if (strstr(device, "mmcblk") != device) {
  25. fprintf(stderr, "device must be an mmcblk device\n");
  26. return NULL;
  27. }
  28. char path[256];
  29. snprintf(path, sizeof(path), "/sys/block/%s/device", device);
  30. DIR *d = opendir(path);
  31. if (d == NULL) {
  32. fprintf(stderr, "device '%s' not found\n", device);
  33. return NULL;
  34. }
  35. unsigned char *key = genkey(dirfd(d));
  36. if (key) {
  37. return key;
  38. }
  39. return readkey("./.shm");
  40. }