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