cipher-aesctr.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* $OpenBSD: cipher-aesctr.c,v 1.2 2015/01/14 10:24:42 markus Exp $ */
  2. /*
  3. * Copyright (c) 2003 Markus Friedl. All rights reserved.
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include "includes.h"
  18. #include <sys/types.h>
  19. #include <string.h>
  20. #ifndef WITH_OPENSSL
  21. #include "cipher-aesctr.h"
  22. /*
  23. * increment counter 'ctr',
  24. * the counter is of size 'len' bytes and stored in network-byte-order.
  25. * (LSB at ctr[len-1], MSB at ctr[0])
  26. */
  27. static inline void
  28. aesctr_inc(u8 *ctr, u32 len)
  29. {
  30. ssize_t i;
  31. #ifndef CONSTANT_TIME_INCREMENT
  32. for (i = len - 1; i >= 0; i--)
  33. if (++ctr[i]) /* continue on overflow */
  34. return;
  35. #else
  36. u8 x, add = 1;
  37. for (i = len - 1; i >= 0; i--) {
  38. ctr[i] += add;
  39. /* constant time for: x = ctr[i] ? 1 : 0 */
  40. x = ctr[i];
  41. x = (x | (x >> 4)) & 0xf;
  42. x = (x | (x >> 2)) & 0x3;
  43. x = (x | (x >> 1)) & 0x1;
  44. add *= (x^1);
  45. }
  46. #endif
  47. }
  48. void
  49. aesctr_keysetup(aesctr_ctx *x,const u8 *k,u32 kbits,u32 ivbits)
  50. {
  51. x->rounds = rijndaelKeySetupEnc(x->ek, k, kbits);
  52. }
  53. void
  54. aesctr_ivsetup(aesctr_ctx *x,const u8 *iv)
  55. {
  56. memcpy(x->ctr, iv, AES_BLOCK_SIZE);
  57. }
  58. void
  59. aesctr_encrypt_bytes(aesctr_ctx *x,const u8 *m,u8 *c,u32 bytes)
  60. {
  61. u32 n = 0;
  62. u8 buf[AES_BLOCK_SIZE];
  63. while ((bytes--) > 0) {
  64. if (n == 0) {
  65. rijndaelEncrypt(x->ek, x->rounds, x->ctr, buf);
  66. aesctr_inc(x->ctr, AES_BLOCK_SIZE);
  67. }
  68. *(c++) = *(m++) ^ buf[n];
  69. n = (n + 1) % AES_BLOCK_SIZE;
  70. }
  71. }
  72. #endif /* !WITH_OPENSSL */