Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1.  
  2.  
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7.  
  8. #define MAX_SIZE 256
  9.  
  10. void strip_newline(char* to_strip);
  11. void encrypt_data(FILE* input_file, FILE* output_file, char *key);
  12.  
  13. int main(int argc, char* argv[])
  14. {
  15. //Check for valid number of arguments
  16. if (argc != 3)
  17. {
  18. printf("Invalid number of arguments. %d arguments were supplied.\n", argc);
  19. printf("Usage: %s inputfile outputfile\n", argv[0]); //Usage: ./xortest inputfile outputfile
  20. exit(0);
  21. }
  22.  
  23. FILE* input;
  24. FILE* output;
  25.  
  26. //Open input and output files
  27. input = fopen(argv[1], "r");
  28. output = fopen(argv[2], "w");
  29.  
  30.  
  31. //Check input file
  32. if (input == NULL)
  33. {
  34. printf("Input file cannot be read.\n");
  35. exit(0);
  36. }
  37.  
  38. //Check output file
  39. if (output == NULL)
  40. {
  41. printf("Output file cannot be written to.\n");
  42. exit(0);
  43. }
  44.  
  45. //Key strings
  46. char *key = malloc(MAX_SIZE);
  47.  
  48. //Prompt for key
  49. printf("Passphrase: ");
  50.  
  51. //Read in key
  52. fgets(key, MAX_SIZE, stdin);
  53.  
  54. printf("Encrypting %s\n", argv[1]);
  55.  
  56. //strip newlines
  57. strip_newline(key);
  58.  
  59. //XOR data and write it to file
  60.  
  61. encrypt_data(input, output, key);
  62.  
  63. printf("Encrypted data written to %s\n", argv[2]);
  64.  
  65. free(key);
  66.  
  67. //Close files
  68. fclose(input);
  69. fclose(output);
  70.  
  71. return 0;
  72.  
  73. }
  74.  
  75.  
  76. void encrypt_data(FILE* input_file, FILE* output_file, char* key)
  77. {
  78. int key_count = 0; //Used to restart key if strlen(key) < strlen(encrypt)
  79. int encrypt_byte;
  80.  
  81. while( (encrypt_byte = fgetc(input_file)) != EOF) //Loop through each byte of file until EOF
  82. {
  83. //XOR the data and write it to a file
  84. fputc(encrypt_byte ^ key[key_count], output_file);
  85.  
  86. //Increment key_count and start over if necessary
  87. key_count++;
  88. if(key_count == strlen(key))
  89. key_count = 0;
  90. }
  91. }
  92.  
  93. void strip_newline(char* to_strip)
  94. {
  95. //remove newlines
  96. if (to_strip[strlen(to_strip) - 1] == '\n')
  97. {
  98. to_strip[strlen(to_strip) - 1] = '\0';
  99. }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement