xref: /openbsd-src/lib/libcrypto/rc4/rc4.c (revision 902bfdca5279bfeffc5b4c006292470a4b73c32a)
1 /* $OpenBSD: rc4.c,v 1.13 2025/01/27 14:02:32 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
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 RC4_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 	i = len >> 3;
208 	if (i) {
209 		for (;;) {
210 			RC4_LOOP(indata[0], outdata[0]);
211 			RC4_LOOP(indata[1], outdata[1]);
212 			RC4_LOOP(indata[2], outdata[2]);
213 			RC4_LOOP(indata[3], outdata[3]);
214 			RC4_LOOP(indata[4], outdata[4]);
215 			RC4_LOOP(indata[5], outdata[5]);
216 			RC4_LOOP(indata[6], outdata[6]);
217 			RC4_LOOP(indata[7], outdata[7]);
218 
219 			indata += 8;
220 			outdata += 8;
221 
222 			if (--i == 0)
223 				break;
224 		}
225 	}
226 	i = len&0x07;
227 	if (i) {
228 		for (;;) {
229 			RC4_LOOP(indata[0], outdata[0]);
230 			if (--i == 0)
231 				break;
232 			RC4_LOOP(indata[1], outdata[1]);
233 			if (--i == 0)
234 				break;
235 			RC4_LOOP(indata[2], outdata[2]);
236 			if (--i == 0)
237 				break;
238 			RC4_LOOP(indata[3], outdata[3]);
239 			if (--i == 0)
240 				break;
241 			RC4_LOOP(indata[4], outdata[4]);
242 			if (--i == 0)
243 				break;
244 			RC4_LOOP(indata[5], outdata[5]);
245 			if (--i == 0)
246 				break;
247 			RC4_LOOP(indata[6], outdata[6]);
248 			if (--i == 0)
249 				break;
250 		}
251 	}
252 	key->x = x;
253 	key->y = y;
254 }
255 #endif
256 
257 #ifdef HAVE_RC4_SET_KEY_INTERNAL
258 void rc4_set_key_internal(RC4_KEY *key, int len, const unsigned char *data);
259 
260 #else
261 static inline void
262 rc4_set_key_internal(RC4_KEY *key, int len, const unsigned char *data)
263 {
264 	RC4_INT tmp;
265 	int id1, id2;
266 	RC4_INT *d;
267 	unsigned int i;
268 
269 	d = &(key->data[0]);
270 	key->x = 0;
271 	key->y = 0;
272 	id1 = id2 = 0;
273 
274 #define SK_LOOP(d,n) { \
275 		tmp=d[(n)]; \
276 		id2 = (data[id1] + tmp + id2) & 0xff; \
277 		if (++id1 == len) id1=0; \
278 		d[(n)]=d[id2]; \
279 		d[id2]=tmp; }
280 
281 	for (i = 0; i < 256; i++)
282 		d[i] = i;
283 	for (i = 0; i < 256; i += 4) {
284 		SK_LOOP(d, i + 0);
285 		SK_LOOP(d, i + 1);
286 		SK_LOOP(d, i + 2);
287 		SK_LOOP(d, i + 3);
288 	}
289 }
290 #endif
291 
292 void
293 RC4(RC4_KEY *key, size_t len, const unsigned char *indata,
294     unsigned char *outdata)
295 {
296 	rc4_internal(key, len, indata, outdata);
297 }
298 LCRYPTO_ALIAS(RC4);
299 
300 void
301 RC4_set_key(RC4_KEY *key, int len, const unsigned char *data)
302 {
303 	rc4_set_key_internal(key, len, data);
304 }
305 LCRYPTO_ALIAS(RC4_set_key);
306