password.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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) return found;
  32. if (check) {
  33. if (data[i] == ':') found = 1;
  34. if (suffix[suffixCount] != data[i]) check = 0;
  35. suffixCount++;
  36. }
  37. if (data[i] == '\n') {
  38. check = 1;
  39. suffixCount = 0;
  40. }
  41. }
  42. return found;
  43. }
  44. void usage(char *app) {
  45. printf("Usage:\n%s <password>\n", app);
  46. }
  47. int main(int argc, char **argv) {
  48. if (argc < 2) {
  49. usage(argv[0]);
  50. return 1;
  51. }
  52. char *hash = getHash(argv[1]);
  53. char *url = getURL(hash);
  54. char *suffix = getSuffixUppercase(hash);
  55. free(hash);
  56. char *data = getData(url);
  57. free(url);
  58. if (findSuffix(suffix, data)) puts("Your password is well known!");
  59. free(data);
  60. free(suffix);
  61. }