1
0

nacl-sha256.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. commandline/nacl-sha256.c version 20080713
  3. D. J. Bernstein
  4. Public domain.
  5. */
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <sys/mman.h>
  9. #include <unistd.h>
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include "crypto_hash_sha256.h"
  14. unsigned char *input;
  15. unsigned long long inputalloc;
  16. unsigned long long inputlen;
  17. unsigned char h[crypto_hash_sha256_BYTES];
  18. void h_print(void)
  19. {
  20. int i;
  21. for (i = 0;i < crypto_hash_sha256_BYTES;++i) printf("%02x",255 & (int) h[i]);
  22. printf("\n");
  23. }
  24. int main()
  25. {
  26. struct stat st;
  27. int ch;
  28. if (fstat(0,&st) == 0) {
  29. input = mmap(0,st.st_size,PROT_READ,MAP_SHARED,0,0);
  30. if (input != MAP_FAILED) {
  31. crypto_hash_sha256(h,input,st.st_size);
  32. h_print();
  33. return 0;
  34. }
  35. }
  36. input = 0;
  37. inputalloc = 0;
  38. inputlen = 0;
  39. while ((ch = getchar()) != EOF) {
  40. if (inputlen >= inputalloc) {
  41. void *newinput;
  42. while (inputlen >= inputalloc)
  43. inputalloc = inputalloc * 2 + 1;
  44. if (posix_memalign(&newinput,16,inputalloc) != 0) return 111;
  45. memcpy(newinput,input,inputlen);
  46. free(input);
  47. input = newinput;
  48. }
  49. input[inputlen++] = ch;
  50. }
  51. crypto_hash_sha256(h,input,inputlen);
  52. h_print();
  53. return 0;
  54. }