ctr_encrypt.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 CTR
  13. int ctr_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CTR *ctr)
  14. {
  15. int x, err;
  16. _ARGCHK(pt != NULL);
  17. _ARGCHK(ct != NULL);
  18. _ARGCHK(ctr != NULL);
  19. if ((err = cipher_is_valid(ctr->cipher)) != CRYPT_OK) {
  20. return err;
  21. }
  22. /* is blocklen/padlen valid? */
  23. if (ctr->blocklen < 0 || ctr->blocklen > (int)sizeof(ctr->ctr) ||
  24. ctr->padlen < 0 || ctr->padlen > (int)sizeof(ctr->pad)) {
  25. return CRYPT_INVALID_ARG;
  26. }
  27. while (len-- > 0) {
  28. /* is the pad empty? */
  29. if (ctr->padlen == ctr->blocklen) {
  30. /* increment counter */
  31. if (ctr->mode == 0) {
  32. /* little-endian */
  33. for (x = 0; x < ctr->blocklen; x++) {
  34. ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255;
  35. if (ctr->ctr[x] != (unsigned char)0) {
  36. break;
  37. }
  38. }
  39. } else {
  40. /* big-endian */
  41. for (x = ctr->blocklen-1; x >= 0; x--) {
  42. ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255;
  43. if (ctr->ctr[x] != (unsigned char)0) {
  44. break;
  45. }
  46. }
  47. }
  48. /* encrypt it */
  49. cipher_descriptor[ctr->cipher].ecb_encrypt(ctr->ctr, ctr->pad, &ctr->key);
  50. ctr->padlen = 0;
  51. }
  52. *ct++ = *pt++ ^ ctr->pad[ctr->padlen++];
  53. }
  54. return CRYPT_OK;
  55. }
  56. #endif