cbc_encrypt.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis
  2. *
  3. * LibTomCrypt is a library that provides various cryptographic
  4. * algorithms in a highly modular and flexible manner.
  5. *
  6. * The library is free for all purposes without any express
  7. * guarantee it works.
  8. *
  9. * Tom St Denis, [email protected], http://libtomcrypt.org
  10. */
  11. #include "mycrypt.h"
  12. #ifdef CBC
  13. int cbc_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_CBC *cbc)
  14. {
  15. int x, err;
  16. unsigned char tmp[MAXBLOCKSIZE];
  17. _ARGCHK(pt != NULL);
  18. _ARGCHK(ct != NULL);
  19. _ARGCHK(cbc != NULL);
  20. if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) {
  21. return err;
  22. }
  23. /* is blocklen valid? */
  24. if (cbc->blocklen < 0 || cbc->blocklen > (int)sizeof(cbc->IV)) {
  25. return CRYPT_INVALID_ARG;
  26. }
  27. /* xor IV against plaintext */
  28. for (x = 0; x < cbc->blocklen; x++) {
  29. tmp[x] = pt[x] ^ cbc->IV[x];
  30. }
  31. /* encrypt */
  32. cipher_descriptor[cbc->cipher].ecb_encrypt(tmp, ct, &cbc->key);
  33. /* store IV [ciphertext] for a future block */
  34. for (x = 0; x < cbc->blocklen; x++) {
  35. cbc->IV[x] = ct[x];
  36. }
  37. #ifdef CLEAN_STACK
  38. zeromem(tmp, sizeof(tmp));
  39. #endif
  40. return CRYPT_OK;
  41. }
  42. #endif