Advertisement
Slyfoxx724

extra5.c xor encrypt

Dec 7th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. 1 #include <stdio.h>
  2. 2 #include <string.h>
  3. 3 #include <stdlib.h>
  4. 4
  5. 5 int encrypt_data(FILE *);
  6. 6
  7. 7 int main(void)
  8. 8 {
  9. 9 FILE *file_ptr;
  10. 10 int return_code;
  11. 11 char file_name[50];
  12. 12
  13. 13 printf("What would you like to name your file to be encrypted?\n");
  14. 14 scanf("%s", &file_name);
  15. 15
  16. 16 file_ptr = fopen(file_name, "r+");
  17. 17
  18. 18 if(file_ptr == NULL)
  19. 19 printf("File does not exist.\n");
  20. 20 else
  21. 21 printf("File exists.\n");
  22. 22
  23. 23
  24. 24
  25. 25 return_code = encrypt_data(file_ptr);
  26. 26 fclose(file_ptr);
  27. 27 printf("\n");
  28. 28 return 0;
  29. 29 }
  30. 30
  31. 31 int encrypt_data(FILE *disk_file_ptr)
  32. 32 {
  33. 33 int i;
  34. 34 unsigned long int file_size;
  35. 35 int key_length;
  36. 36 char *file_buffer = NULL;
  37. 37
  38. 38 char key[] = "ABCDEF";
  39. 39
  40. 40 key_length = strlen(key);
  41. 41
  42. 42 fseek(disk_file_ptr, 0, SEEK_END);
  43. 43 file_size = ftell(disk_file_ptr);
  44. 44
  45. 45 rewind(disk_file_ptr);
  46. 46
  47. 47 file_buffer = malloc(file_size);
  48. 48
  49. 49 if(fread(file_buffer, file_size, 1, disk_file_ptr) != 1)
  50. 50 {
  51. 51 printf("Error in reading file\n");
  52. 52 return -1;
  53. 53 }
  54. 54
  55. 55 for(i=0; i<file_size; i++)
  56. 56 {
  57. 57 file_buffer[i] = file_buffer[i]^key[i%key_length];
  58. 58 }
  59. 59
  60. 60 rewind(disk_file_ptr);
  61. 61
  62. 62 if(fwrite(file_buffer, file_size, 1, disk_file_ptr) != 1)
  63. 63 {
  64. 64 printf("Error in writing encrypted data to file\n");
  65. 65 return -1;
  66. 66 }
  67. 67
  68. 68 free(file_buffer);
  69. 69
  70. 70 return 0;
  71. 71 }
  72. 72
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement