example4.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. /* NOCW */
  2. /*
  3. Please read the README file for condition of use, before
  4. using this software.
  5. Maurice Gittens <mgittens@gits.nl> January 1997
  6. */
  7. #include <stdio.h>
  8. #include <unistd.h>
  9. #include <fcntl.h>
  10. #include <sys/stat.h>
  11. #include <openssl/evp.h>
  12. #define STDIN 0
  13. #define STDOUT 1
  14. #define BUFLEN 512
  15. static const char *usage = "Usage: example4 [-d]\n";
  16. void do_encode(void);
  17. void do_decode(void);
  18. int main(int argc, char *argv[])
  19. {
  20. if ((argc == 1))
  21. {
  22. do_encode();
  23. }
  24. else if ((argc == 2) && !strcmp(argv[1],"-d"))
  25. {
  26. do_decode();
  27. }
  28. else
  29. {
  30. fprintf(stderr,"%s", usage);
  31. exit(1);
  32. }
  33. return 0;
  34. }
  35. void do_encode()
  36. {
  37. char buf[BUFLEN];
  38. char ebuf[BUFLEN+24];
  39. unsigned int ebuflen;
  40. EVP_ENCODE_CTX ectx;
  41. EVP_EncodeInit(&ectx);
  42. while(1)
  43. {
  44. int readlen = read(STDIN, buf, sizeof(buf));
  45. if (readlen <= 0)
  46. {
  47. if (!readlen)
  48. break;
  49. else
  50. {
  51. perror("read");
  52. exit(1);
  53. }
  54. }
  55. EVP_EncodeUpdate(&ectx, ebuf, &ebuflen, buf, readlen);
  56. write(STDOUT, ebuf, ebuflen);
  57. }
  58. EVP_EncodeFinal(&ectx, ebuf, &ebuflen);
  59. write(STDOUT, ebuf, ebuflen);
  60. }
  61. void do_decode()
  62. {
  63. char buf[BUFLEN];
  64. char ebuf[BUFLEN+24];
  65. unsigned int ebuflen;
  66. EVP_ENCODE_CTX ectx;
  67. EVP_DecodeInit(&ectx);
  68. while(1)
  69. {
  70. int readlen = read(STDIN, buf, sizeof(buf));
  71. int rc;
  72. if (readlen <= 0)
  73. {
  74. if (!readlen)
  75. break;
  76. else
  77. {
  78. perror("read");
  79. exit(1);
  80. }
  81. }
  82. rc = EVP_DecodeUpdate(&ectx, ebuf, &ebuflen, buf, readlen);
  83. if (rc <= 0)
  84. {
  85. if (!rc)
  86. {
  87. write(STDOUT, ebuf, ebuflen);
  88. break;
  89. }
  90. fprintf(stderr, "Error: decoding message\n");
  91. return;
  92. }
  93. write(STDOUT, ebuf, ebuflen);
  94. }
  95. EVP_DecodeFinal(&ectx, ebuf, &ebuflen);
  96. write(STDOUT, ebuf, ebuflen);
  97. }