ofb128.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright 2008-2020 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <string.h>
  10. #include <openssl/crypto.h>
  11. #include "crypto/modes.h"
  12. #if defined(__GNUC__) && !defined(STRICT_ALIGNMENT)
  13. typedef size_t size_t_aX __attribute((__aligned__(1)));
  14. #else
  15. typedef size_t size_t_aX;
  16. #endif
  17. /*
  18. * The input and output encrypted as though 128bit ofb mode is being used.
  19. * The extra state information to record how much of the 128bit block we have
  20. * used is contained in *num;
  21. */
  22. void CRYPTO_ofb128_encrypt(const unsigned char *in, unsigned char *out,
  23. size_t len, const void *key,
  24. unsigned char ivec[16], int *num, block128_f block)
  25. {
  26. unsigned int n;
  27. size_t l = 0;
  28. n = *num;
  29. #if !defined(OPENSSL_SMALL_FOOTPRINT)
  30. if (16 % sizeof(size_t) == 0) { /* always true actually */
  31. do {
  32. while (n && len) {
  33. *(out++) = *(in++) ^ ivec[n];
  34. --len;
  35. n = (n + 1) % 16;
  36. }
  37. # if defined(STRICT_ALIGNMENT)
  38. if (((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) !=
  39. 0)
  40. break;
  41. # endif
  42. while (len >= 16) {
  43. (*block) (ivec, ivec, key);
  44. for (; n < 16; n += sizeof(size_t))
  45. *(size_t_aX *)(out + n) =
  46. *(size_t_aX *)(in + n)
  47. ^ *(size_t_aX *)(ivec + n);
  48. len -= 16;
  49. out += 16;
  50. in += 16;
  51. n = 0;
  52. }
  53. if (len) {
  54. (*block) (ivec, ivec, key);
  55. while (len--) {
  56. out[n] = in[n] ^ ivec[n];
  57. ++n;
  58. }
  59. }
  60. *num = n;
  61. return;
  62. } while (0);
  63. }
  64. /* the rest would be commonly eliminated by x86* compiler */
  65. #endif
  66. while (l < len) {
  67. if (n == 0) {
  68. (*block) (ivec, ivec, key);
  69. }
  70. out[l] = in[l] ^ ivec[n];
  71. ++l;
  72. n = (n + 1) % 16;
  73. }
  74. *num = n;
  75. }