i_skey.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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/idea.h>
  10. #include "idea_lcl.h"
  11. static IDEA_INT inverse(unsigned int xin);
  12. void IDEA_set_encrypt_key(const unsigned char *key, IDEA_KEY_SCHEDULE *ks)
  13. {
  14. int i;
  15. register IDEA_INT *kt, *kf, r0, r1, r2;
  16. kt = &(ks->data[0][0]);
  17. n2s(key, kt[0]);
  18. n2s(key, kt[1]);
  19. n2s(key, kt[2]);
  20. n2s(key, kt[3]);
  21. n2s(key, kt[4]);
  22. n2s(key, kt[5]);
  23. n2s(key, kt[6]);
  24. n2s(key, kt[7]);
  25. kf = kt;
  26. kt += 8;
  27. for (i = 0; i < 6; i++) {
  28. r2 = kf[1];
  29. r1 = kf[2];
  30. *(kt++) = ((r2 << 9) | (r1 >> 7)) & 0xffff;
  31. r0 = kf[3];
  32. *(kt++) = ((r1 << 9) | (r0 >> 7)) & 0xffff;
  33. r1 = kf[4];
  34. *(kt++) = ((r0 << 9) | (r1 >> 7)) & 0xffff;
  35. r0 = kf[5];
  36. *(kt++) = ((r1 << 9) | (r0 >> 7)) & 0xffff;
  37. r1 = kf[6];
  38. *(kt++) = ((r0 << 9) | (r1 >> 7)) & 0xffff;
  39. r0 = kf[7];
  40. *(kt++) = ((r1 << 9) | (r0 >> 7)) & 0xffff;
  41. r1 = kf[0];
  42. if (i >= 5)
  43. break;
  44. *(kt++) = ((r0 << 9) | (r1 >> 7)) & 0xffff;
  45. *(kt++) = ((r1 << 9) | (r2 >> 7)) & 0xffff;
  46. kf += 8;
  47. }
  48. }
  49. void IDEA_set_decrypt_key(IDEA_KEY_SCHEDULE *ek, IDEA_KEY_SCHEDULE *dk)
  50. {
  51. int r;
  52. register IDEA_INT *fp, *tp, t;
  53. tp = &(dk->data[0][0]);
  54. fp = &(ek->data[8][0]);
  55. for (r = 0; r < 9; r++) {
  56. *(tp++) = inverse(fp[0]);
  57. *(tp++) = ((int)(0x10000L - fp[2]) & 0xffff);
  58. *(tp++) = ((int)(0x10000L - fp[1]) & 0xffff);
  59. *(tp++) = inverse(fp[3]);
  60. if (r == 8)
  61. break;
  62. fp -= 6;
  63. *(tp++) = fp[4];
  64. *(tp++) = fp[5];
  65. }
  66. tp = &(dk->data[0][0]);
  67. t = tp[1];
  68. tp[1] = tp[2];
  69. tp[2] = t;
  70. t = tp[49];
  71. tp[49] = tp[50];
  72. tp[50] = t;
  73. }
  74. /* taken directly from the 'paper' I'll have a look at it later */
  75. static IDEA_INT inverse(unsigned int xin)
  76. {
  77. long n1, n2, q, r, b1, b2, t;
  78. if (xin == 0)
  79. b2 = 0;
  80. else {
  81. n1 = 0x10001;
  82. n2 = xin;
  83. b2 = 1;
  84. b1 = 0;
  85. do {
  86. r = (n1 % n2);
  87. q = (n1 - r) / n2;
  88. if (r == 0) {
  89. if (b2 < 0)
  90. b2 = 0x10001 + b2;
  91. } else {
  92. n1 = n2;
  93. n2 = r;
  94. t = b2;
  95. b2 = b1 - q * b2;
  96. b1 = t;
  97. }
  98. } while (r != 0);
  99. }
  100. return (IDEA_INT)b2;
  101. }