pwned.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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(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(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. int findSuffix(char *suffix, char *data) {
  27. int found = 0;
  28. int check = 1;
  29. int suffixCount = 0;
  30. for (unsigned long i = 0; i < strlen(data); i++) {
  31. if (found) {
  32. putchar(data[i]);
  33. if (data[i] == '\n') return found;
  34. }
  35. if (check) {
  36. if (data[i] == ':') {
  37. puts("This is how many times your password was pwned:");
  38. found = 1;
  39. }
  40. if (suffix[suffixCount] != data[i]) check = 0;
  41. suffixCount++;
  42. }
  43. if (data[i] == '\n') {
  44. check = 1;
  45. suffixCount = 0;
  46. }
  47. }
  48. return found;
  49. }
  50. void usage(char *app) {
  51. printf("Usage:\n%s <password>\n", app);
  52. }
  53. int main(int argc, char **argv) {
  54. if (argc < 2) {
  55. usage(argv[0]);
  56. return 1;
  57. }
  58. char *hash = getHash(argv[1]);
  59. char *url = getURL(hash);
  60. char *suffix = getSuffixUppercase(hash);
  61. free(hash);
  62. char *data = getData(url);
  63. free(url);
  64. if (!findSuffix(suffix, data)) puts("Password not pwned!");
  65. free(data);
  66. free(suffix);
  67. }