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