歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言寫的一個簡單文件加密程序

C語言寫的一個簡單文件加密程序

日期:2017/3/1 10:10:20   编辑:Linux編程

C語言寫的一個簡單文件加密程序:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. int decrypt(FILE *in,FILE *out);
  5. int encrypt(FILE *in,FILE *out);
  6. unsigned char atoh(char *hexstr);
  7. int main(int argc,char **argv)
  8. {
  9. if(argc > 1 && strcmp(argv[1],"--help") == 0)
  10. {
  11. printf("\nusage: linkrules_god [-e|-d] inputfile outputfile\n");
  12. printf(" -e encrypt inputfile to outputfile.\n");
  13. printf(" -d decrypt inputfile to outputfile.\n\n");
  14. exit(0);
  15. }
  16. if(argc != 4)
  17. {
  18. fprintf(stderr,"%s\n","please using --help go get help.");
  19. exit(-1);
  20. }
  21. FILE *in = fopen(argv[2],"rb");
  22. FILE *out = fopen(argv[3],"w");
  23. if(in == NULL || out == NULL)
  24. {
  25. fprintf(stderr,"%s\n","open file error!");
  26. exit(1);
  27. }
  28. if(argv[1][1] == 'e')
  29. {
  30. encrypt(in,out);
  31. }
  32. else if(argv[1][1] == 'd')
  33. {
  34. decrypt(in,out);
  35. }
  36. fclose(in);
  37. fclose(out);
  38. return 0;
  39. }
  40. int encrypt(FILE *in,FILE *out)
  41. {
  42. if(in == NULL || out == NULL)
  43. {
  44. fprintf(stderr,"%s\n","file error!\n");
  45. return -1;
  46. }
  47. unsigned char hex;
  48. while(fread(&hex,1,1,in))
  49. {
  50. hex = ~hex^0x92;
  51. fprintf(out,"%02X",hex);
  52. }
  53. return 0;
  54. }
  55. int decrypt(FILE *in,FILE *out)
  56. {
  57. if(in == NULL || out == NULL)
  58. {
  59. fprintf(stderr,"%s\n","file error!");
  60. return -1;
  61. }
  62. unsigned char hexstr[3];
  63. unsigned char hex = 0;
  64. int i = 0;
  65. while(fread(&hexstr,2,1,in))
  66. {
  67. hex = atoh(hexstr);
  68. hex = ~(hex ^ 0x92);
  69. fwrite(&hex,1,1,out);
  70. }
  71. return 0;
  72. }
  73. /* convert string to hex */
  74. unsigned char atoh(char *hexstr)
  75. {
  76. int hextodec[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
  77. char chtodec[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  78. unsigned char hexnum = 0;
  79. for(int i = 0; i < sizeof(chtodec); ++i)
  80. {
  81. if(hexstr[0] == chtodec[i])
  82. {
  83. hexnum += hextodec[i]*16;
  84. }
  85. }
  86. for(int i = 0; i < sizeof(chtodec); ++i)
  87. {
  88. if(hexstr[1] == chtodec[i])
  89. {
  90. hexnum += hextodec[i];
  91. }
  92. }
  93. return hexnum;
  94. }

encrypt -e sourcefile outputfile 加密

encrypt -d sourcefile outputfile 解密

encrypt --help 幫助

輸出的加密文件中的內容:

Copyright © Linux教程網 All Rights Reserved