decrypt.c 983 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #define _XOPEN_SOURCE 700
  2. #include <errno.h>
  3. #include <fcntl.h>
  4. #include <libgen.h>
  5. #include <stdio.h>
  6. #include <sys/mman.h>
  7. #include <sys/stat.h>
  8. #include <string.h>
  9. #include <unistd.h>
  10. #include "deonebook.h"
  11. #define CBC 1
  12. #define ECB 0
  13. #define CTR 0
  14. #include "tiny-AES-c/aes.c"
  15. int decrypt(const unsigned char *key, const char *in, const char *out)
  16. {
  17. int fd = open(in, O_RDONLY);
  18. if (fd == -1) {
  19. perror(in);
  20. return 1;
  21. }
  22. struct stat st;
  23. if (fstat(fd, &st) != 0) {
  24. perror(in);
  25. return 1;
  26. }
  27. unsigned char *buf = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
  28. if (buf == MAP_FAILED) {
  29. perror(in);
  30. return 1;
  31. }
  32. close(fd);
  33. unsigned char iv[IV_SIZE];
  34. memset(iv, '\03', sizeof(iv));
  35. struct AES_ctx ctx = {0};
  36. AES_init_ctx_iv(&ctx, key, iv);
  37. AES_CBC_decrypt_buffer(&ctx, buf, st.st_size);
  38. fd = open(out, O_WRONLY | O_CREAT, 0644);
  39. if (fd == -1) {
  40. perror(out);
  41. return 1;
  42. }
  43. write(fd, buf, st.st_size);
  44. close(fd);
  45. return 0;
  46. }