cbc_decrypt.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_CBC *cbc)
  14. {
  15. int x, err;
  16. unsigned char tmp[MAXBLOCKSIZE], tmp2[MAXBLOCKSIZE];
  17. _ARGCHK(pt != NULL);
  18. _ARGCHK(ct != NULL);
  19. _ARGCHK(cbc != NULL);
  20. /* decrypt the block from ct into tmp */
  21. if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) {
  22. return err;
  23. }
  24. _ARGCHK(cipher_descriptor[cbc->cipher].ecb_decrypt != NULL);
  25. /* is blocklen valid? */
  26. if (cbc->blocklen < 0 || cbc->blocklen > (int)sizeof(cbc->IV)) {
  27. return CRYPT_INVALID_ARG;
  28. }
  29. /* decrypt and xor IV against the plaintext of the previous step */
  30. cipher_descriptor[cbc->cipher].ecb_decrypt(ct, tmp, &cbc->key);
  31. for (x = 0; x < cbc->blocklen; x++) {
  32. /* copy CT in case ct == pt */
  33. tmp2[x] = ct[x];
  34. /* actually decrypt the byte */
  35. pt[x] = tmp[x] ^ cbc->IV[x];
  36. }
  37. /* replace IV with this current ciphertext */
  38. for (x = 0; x < cbc->blocklen; x++) {
  39. cbc->IV[x] = tmp2[x];
  40. }
  41. #ifdef CLEAN_STACK
  42. zeromem(tmp, sizeof(tmp));
  43. zeromem(tmp2, sizeof(tmp2));
  44. #endif
  45. return CRYPT_OK;
  46. }
  47. #endif