example3.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. #define INIT_VECTOR "12345678"
  16. #define ENCRYPT 1
  17. #define DECRYPT 0
  18. #define ALG EVP_des_ede3_cbc()
  19. static const char *usage = "Usage: example3 [-d] password\n";
  20. void do_cipher(char *,int);
  21. int main(int argc, char *argv[])
  22. {
  23. if ((argc == 2))
  24. {
  25. do_cipher(argv[1],ENCRYPT);
  26. }
  27. else if ((argc == 3) && !strcmp(argv[1],"-d"))
  28. {
  29. do_cipher(argv[2],DECRYPT);
  30. }
  31. else
  32. {
  33. fprintf(stderr,"%s", usage);
  34. exit(1);
  35. }
  36. return 0;
  37. }
  38. void do_cipher(char *pw, int operation)
  39. {
  40. char buf[BUFLEN];
  41. char ebuf[BUFLEN + 8];
  42. unsigned int ebuflen; /* rc; */
  43. unsigned char iv[EVP_MAX_IV_LENGTH], key[EVP_MAX_KEY_LENGTH];
  44. /* unsigned int ekeylen, net_ekeylen; */
  45. EVP_CIPHER_CTX ectx;
  46. memcpy(iv, INIT_VECTOR, sizeof(iv));
  47. EVP_BytesToKey(ALG, EVP_md5(), "salu", pw, strlen(pw), 1, key, iv);
  48. EVP_CIPHER_CTX_init(&ectx);
  49. EVP_CipherInit_ex(&ectx, ALG, NULL, key, iv, operation);
  50. while(1)
  51. {
  52. int readlen = read(STDIN, buf, sizeof(buf));
  53. if (readlen <= 0)
  54. {
  55. if (!readlen)
  56. break;
  57. else
  58. {
  59. perror("read");
  60. exit(1);
  61. }
  62. }
  63. EVP_CipherUpdate(&ectx, ebuf, &ebuflen, buf, readlen);
  64. write(STDOUT, ebuf, ebuflen);
  65. }
  66. EVP_CipherFinal_ex(&ectx, ebuf, &ebuflen);
  67. EVP_CIPHER_CTX_cleanup(&ectx);
  68. write(STDOUT, ebuf, ebuflen);
  69. }