pwned.c 1.7 KB

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