pwned.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <ctype.h>
  2. #include "curl.h"
  3. #include "sha.h"
  4. // https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange
  5. #define HASH_PREFIX_SIZE 5
  6. #define HASH_SUFFIX_SIZE 35
  7. #define URL_SIZE 43
  8. char *getURL(const char* hash) {
  9. const char *baseURL = "https://api.pwnedpasswords.com/range/";
  10. char *url = calloc(URL_SIZE, 1);
  11. strncpy(url, baseURL, strlen(baseURL));
  12. strncat(url, hash, HASH_PREFIX_SIZE);
  13. return url;
  14. }
  15. char *getSuffixUppercase(const char *hash) {
  16. char hashSuffix[HASH_SUFFIX_SIZE + 1];
  17. strncpy(hashSuffix, hash+HASH_PREFIX_SIZE, HASH_SUFFIX_SIZE);
  18. char *suffixUpper = malloc(HASH_SUFFIX_SIZE + 1);
  19. for (int i = 0; i < HASH_SUFFIX_SIZE; i++) {
  20. int c = hashSuffix[i];
  21. if (islower(c)) c = toupper(c);
  22. sprintf(suffixUpper+i, "%c", c);
  23. }
  24. return suffixUpper;
  25. }
  26. void printNumber(const char *data) {
  27. for (int i = 0; data[i] != '\n'; i++)
  28. putchar(data[i]);
  29. putchar('\n');
  30. }
  31. int findSuffix(const char *suffix, const char *data) {
  32. for (int i = 0; data[i] != 0; i++) {
  33. int j;
  34. for (j = 0; suffix[j] != 0; j++)
  35. if (data[i+j] != suffix[j])
  36. break;
  37. if (suffix[j] == 0 && data[i+j] == ':') {
  38. printf("This is how many times your password was pwned: ");
  39. printNumber(data+i+j+1);
  40. return 1;
  41. }
  42. }
  43. return 0;
  44. }
  45. void usage(const char *app) {
  46. printf("Usage:\n%s <password>\n", app);
  47. }
  48. int main(int argc, char **argv) {
  49. if (argc < 2) {
  50. usage(argv[0]);
  51. return 1;
  52. }
  53. char *hash = getHash(argv[1]);
  54. char *url = getURL(hash);
  55. char *suffix = getSuffixUppercase(hash);
  56. free(hash);
  57. char *data = getData(url);
  58. free(url);
  59. if (!findSuffix(suffix, data)) puts("Password not pwned!");
  60. free(data);
  61. free(suffix);
  62. }