pwned.c 1.7 KB

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