sha.c 952 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "sha.h"
  2. static unsigned char *generateHash(const char *string, size_t length) {
  3. unsigned char *hash = malloc(SHA_DIGEST_LENGTH);
  4. if (hash == NULL) {
  5. puts("Couldn't allocate memory for hash!");
  6. return NULL;
  7. }
  8. SHA1((unsigned char*)string, length, hash);
  9. return hash;
  10. }
  11. static char *hashToString(unsigned char *hash) {
  12. char *string = malloc(2 * SHA_DIGEST_LENGTH + 1);
  13. if (string == NULL) {
  14. puts("Couldn't allocate memory for string!");
  15. return NULL;
  16. }
  17. for(int i = 0; i < SHA_DIGEST_LENGTH; i++)
  18. sprintf(string+(i*2), "%02x", hash[i]);
  19. return string;
  20. }
  21. char *getHash(const char *string) {
  22. size_t length = strlen(string);
  23. unsigned char *hash = generateHash(string, length);
  24. if (hash == NULL) {
  25. puts("Couldn't generate hash!");
  26. return NULL;
  27. }
  28. char *hashString = hashToString(hash);
  29. if (hashString == NULL) {
  30. puts("Couldn't convert hash to string!");
  31. return NULL;
  32. }
  33. free(hash);
  34. return hashString;
  35. }