rc5_skey.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright 1995-2016 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 <openssl/rc5.h>
  10. #include "rc5_local.h"
  11. int RC5_32_set_key(RC5_32_KEY *key, int len, const unsigned char *data,
  12. int rounds)
  13. {
  14. RC5_32_INT L[64], l, ll, A, B, *S, k;
  15. int i, j, m, c, t, ii, jj;
  16. if (len > 255)
  17. return 0;
  18. if ((rounds != RC5_16_ROUNDS) &&
  19. (rounds != RC5_12_ROUNDS) && (rounds != RC5_8_ROUNDS))
  20. rounds = RC5_16_ROUNDS;
  21. key->rounds = rounds;
  22. S = &(key->data[0]);
  23. j = 0;
  24. for (i = 0; i <= (len - 8); i += 8) {
  25. c2l(data, l);
  26. L[j++] = l;
  27. c2l(data, l);
  28. L[j++] = l;
  29. }
  30. ii = len - i;
  31. if (ii) {
  32. k = len & 0x07;
  33. c2ln(data, l, ll, k);
  34. L[j + 0] = l;
  35. L[j + 1] = ll;
  36. }
  37. c = (len + 3) / 4;
  38. t = (rounds + 1) * 2;
  39. S[0] = RC5_32_P;
  40. for (i = 1; i < t; i++)
  41. S[i] = (S[i - 1] + RC5_32_Q) & RC5_32_MASK;
  42. j = (t > c) ? t : c;
  43. j *= 3;
  44. ii = jj = 0;
  45. A = B = 0;
  46. for (i = 0; i < j; i++) {
  47. k = (S[ii] + A + B) & RC5_32_MASK;
  48. A = S[ii] = ROTATE_l32(k, 3);
  49. m = (int)(A + B);
  50. k = (L[jj] + A + B) & RC5_32_MASK;
  51. B = L[jj] = ROTATE_l32(k, m);
  52. if (++ii >= t)
  53. ii = 0;
  54. if (++jj >= c)
  55. jj = 0;
  56. }
  57. return 1;
  58. }