xref: /openbsd/lib/libcrypto/rc4/rc4.c (revision 09b34817)
1 /* $OpenBSD: rc4.c,v 1.12 2024/08/11 13:02:39 jsing Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <endian.h>
60 
61 #include <openssl/rc4.h>
62 
63 #include "crypto_arch.h"
64 
65 /* RC4 as implemented from a posting from
66  * Newsgroups: sci.crypt
67  * From: sterndark@netcom.com (David Sterndark)
68  * Subject: RC4 Algorithm revealed.
69  * Message-ID: <sternCvKL4B.Hyy@netcom.com>
70  * Date: Wed, 14 Sep 1994 06:35:31 GMT
71  */
72 
73 #ifdef HAVE_RC4_INTERNAL
74 void rc4_internal(RC4_KEY *key, size_t len, const unsigned char *indata,
75     unsigned char *outdata);
76 
77 #else
78 static void
rc4_internal(RC4_KEY * key,size_t len,const unsigned char * indata,unsigned char * outdata)79 rc4_internal(RC4_KEY *key, size_t len, const unsigned char *indata,
80     unsigned char *outdata)
81 {
82 	RC4_INT *d;
83 	RC4_INT x, y,tx, ty;
84 	size_t i;
85 
86 	x = key->x;
87 	y = key->y;
88 	d = key->data;
89 
90 #if defined(RC4_CHUNK)
91 	/*
92 	 * The original reason for implementing this(*) was the fact that
93 	 * pre-21164a Alpha CPUs don't have byte load/store instructions
94 	 * and e.g. a byte store has to be done with 64-bit load, shift,
95 	 * and, or and finally 64-bit store. Peaking data and operating
96 	 * at natural word size made it possible to reduce amount of
97 	 * instructions as well as to perform early read-ahead without
98 	 * suffering from RAW (read-after-write) hazard. This resulted
99 	 * in ~40%(**) performance improvement on 21064 box with gcc.
100 	 * But it's not only Alpha users who win here:-) Thanks to the
101 	 * early-n-wide read-ahead this implementation also exhibits
102 	 * >40% speed-up on SPARC and 20-30% on 64-bit MIPS (depending
103 	 * on sizeof(RC4_INT)).
104 	 *
105 	 * (*)	"this" means code which recognizes the case when input
106 	 *	and output pointers appear to be aligned at natural CPU
107 	 *	word boundary
108 	 * (**)	i.e. according to 'apps/openssl speed rc4' benchmark,
109 	 *	crypto/rc4/rc4speed.c exhibits almost 70% speed-up...
110 	 *
111 	 * Caveats.
112 	 *
113 	 * - RC4_CHUNK="unsigned long long" should be a #1 choice for
114 	 *   UltraSPARC. Unfortunately gcc generates very slow code
115 	 *   (2.5-3 times slower than one generated by Sun's WorkShop
116 	 *   C) and therefore gcc (at least 2.95 and earlier) should
117 	 *   always be told that RC4_CHUNK="unsigned long".
118 	 *
119 	 *					<appro@fy.chalmers.se>
120 	 */
121 
122 # define RC4_STEP	( \
123 			x=(x+1) &0xff,	\
124 			tx=d[x],	\
125 			y=(tx+y)&0xff,	\
126 			ty=d[y],	\
127 			d[y]=tx,	\
128 			d[x]=ty,	\
129 			(RC4_CHUNK)d[(tx+ty)&0xff]\
130 			)
131 
132 	if ((((size_t)indata & (sizeof(RC4_CHUNK) - 1)) |
133 	    ((size_t)outdata & (sizeof(RC4_CHUNK) - 1))) == 0 ) {
134 		RC4_CHUNK ichunk, otp;
135 
136 		/*
137 		 * I reckon we can afford to implement both endian
138 		 * cases and to decide which way to take at run-time
139 		 * because the machine code appears to be very compact
140 		 * and redundant 1-2KB is perfectly tolerable (i.e.
141 		 * in case the compiler fails to eliminate it:-). By
142 		 * suggestion from Terrel Larson <terr@terralogic.net>.
143 		 *
144 		 * Special notes.
145 		 *
146 		 * - compilers (those I've tried) don't seem to have
147 		 *   problems eliminating either the operators guarded
148 		 *   by "if (sizeof(RC4_CHUNK)==8)" or the condition
149 		 *   expressions themselves so I've got 'em to replace
150 		 *   corresponding #ifdefs from the previous version;
151 		 * - I chose to let the redundant switch cases when
152 		 *   sizeof(RC4_CHUNK)!=8 be (were also #ifdefed
153 		 *   before);
154 		 * - in case you wonder "&(sizeof(RC4_CHUNK)*8-1)" in
155 		 *   [LB]ESHFT guards against "shift is out of range"
156 		 *   warnings when sizeof(RC4_CHUNK)!=8
157 		 *
158 		 *			<appro@fy.chalmers.se>
159 		 */
160 #if BYTE_ORDER == BIG_ENDIAN
161 # define BESHFT(c)	(((sizeof(RC4_CHUNK)-(c)-1)*8)&(sizeof(RC4_CHUNK)*8-1))
162 		for (; len & (0 - sizeof(RC4_CHUNK)); len -= sizeof(RC4_CHUNK)) {
163 			ichunk  = *(RC4_CHUNK *)indata;
164 			otp = RC4_STEP << BESHFT(0);
165 			otp |= RC4_STEP << BESHFT(1);
166 			otp |= RC4_STEP << BESHFT(2);
167 			otp |= RC4_STEP << BESHFT(3);
168 			if (sizeof(RC4_CHUNK) == 8) {
169 				otp |= RC4_STEP << BESHFT(4);
170 				otp |= RC4_STEP << BESHFT(5);
171 				otp |= RC4_STEP << BESHFT(6);
172 				otp |= RC4_STEP << BESHFT(7);
173 			}
174 			*(RC4_CHUNK *)outdata = otp^ichunk;
175 			indata += sizeof(RC4_CHUNK);
176 			outdata += sizeof(RC4_CHUNK);
177 		}
178 #else
179 # define LESHFT(c)	(((c)*8)&(sizeof(RC4_CHUNK)*8-1))
180 		for (; len & (0 - sizeof(RC4_CHUNK)); len -= sizeof(RC4_CHUNK)) {
181 			ichunk = *(RC4_CHUNK *)indata;
182 			otp = RC4_STEP;
183 			otp |= RC4_STEP << 8;
184 			otp |= RC4_STEP << 16;
185 			otp |= RC4_STEP << 24;
186 			if (sizeof(RC4_CHUNK) == 8) {
187 				otp |= RC4_STEP << LESHFT(4);
188 				otp |= RC4_STEP << LESHFT(5);
189 				otp |= RC4_STEP << LESHFT(6);
190 				otp |= RC4_STEP << LESHFT(7);
191 			}
192 			*(RC4_CHUNK *)outdata = otp ^ ichunk;
193 			indata += sizeof(RC4_CHUNK);
194 			outdata += sizeof(RC4_CHUNK);
195 		}
196 #endif
197 	}
198 #endif
199 #define LOOP(in,out) \
200 		x=((x+1)&0xff); \
201 		tx=d[x]; \
202 		y=(tx+y)&0xff; \
203 		d[x]=ty=d[y]; \
204 		d[y]=tx; \
205 		(out) = d[(tx+ty)&0xff]^ (in);
206 
207 #ifndef RC4_INDEX
208 #define RC4_LOOP(a,b,i)	LOOP(*((a)++),*((b)++))
209 #else
210 #define RC4_LOOP(a,b,i)	LOOP(a[i],b[i])
211 #endif
212 
213 	i = len >> 3;
214 	if (i) {
215 		for (;;) {
216 			RC4_LOOP(indata, outdata, 0);
217 			RC4_LOOP(indata, outdata, 1);
218 			RC4_LOOP(indata, outdata, 2);
219 			RC4_LOOP(indata, outdata, 3);
220 			RC4_LOOP(indata, outdata, 4);
221 			RC4_LOOP(indata, outdata, 5);
222 			RC4_LOOP(indata, outdata, 6);
223 			RC4_LOOP(indata, outdata, 7);
224 #ifdef RC4_INDEX
225 			indata += 8;
226 			outdata += 8;
227 #endif
228 			if (--i == 0)
229 				break;
230 		}
231 	}
232 	i = len&0x07;
233 	if (i) {
234 		for (;;) {
235 			RC4_LOOP(indata, outdata, 0);
236 			if (--i == 0)
237 				break;
238 			RC4_LOOP(indata, outdata, 1);
239 			if (--i == 0)
240 				break;
241 			RC4_LOOP(indata, outdata, 2);
242 			if (--i == 0)
243 				break;
244 			RC4_LOOP(indata, outdata, 3);
245 			if (--i == 0)
246 				break;
247 			RC4_LOOP(indata, outdata, 4);
248 			if (--i == 0)
249 				break;
250 			RC4_LOOP(indata, outdata, 5);
251 			if (--i == 0)
252 				break;
253 			RC4_LOOP(indata, outdata, 6);
254 			if (--i == 0)
255 				break;
256 		}
257 	}
258 	key->x = x;
259 	key->y = y;
260 }
261 #endif
262 
263 #ifdef HAVE_RC4_SET_KEY_INTERNAL
264 void rc4_set_key_internal(RC4_KEY *key, int len, const unsigned char *data);
265 
266 #else
267 static inline void
rc4_set_key_internal(RC4_KEY * key,int len,const unsigned char * data)268 rc4_set_key_internal(RC4_KEY *key, int len, const unsigned char *data)
269 {
270 	RC4_INT tmp;
271 	int id1, id2;
272 	RC4_INT *d;
273 	unsigned int i;
274 
275 	d = &(key->data[0]);
276 	key->x = 0;
277 	key->y = 0;
278 	id1 = id2 = 0;
279 
280 #define SK_LOOP(d,n) { \
281 		tmp=d[(n)]; \
282 		id2 = (data[id1] + tmp + id2) & 0xff; \
283 		if (++id1 == len) id1=0; \
284 		d[(n)]=d[id2]; \
285 		d[id2]=tmp; }
286 
287 	for (i = 0; i < 256; i++)
288 		d[i] = i;
289 	for (i = 0; i < 256; i += 4) {
290 		SK_LOOP(d, i + 0);
291 		SK_LOOP(d, i + 1);
292 		SK_LOOP(d, i + 2);
293 		SK_LOOP(d, i + 3);
294 	}
295 }
296 #endif
297 
298 void
RC4(RC4_KEY * key,size_t len,const unsigned char * indata,unsigned char * outdata)299 RC4(RC4_KEY *key, size_t len, const unsigned char *indata,
300     unsigned char *outdata)
301 {
302 	rc4_internal(key, len, indata, outdata);
303 }
304 LCRYPTO_ALIAS(RC4);
305 
306 void
RC4_set_key(RC4_KEY * key,int len,const unsigned char * data)307 RC4_set_key(RC4_KEY *key, int len, const unsigned char *data)
308 {
309 	rc4_set_key_internal(key, len, data);
310 }
311 LCRYPTO_ALIAS(RC4_set_key);
312