2 * An implementation of the ARCFOUR algorithm
4 * Copyright (C) 2006-2007 Christophe Devine
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * The ARCFOUR algorithm was publicly disclosed on 94/09.
23 * http://groups.google.com/group/sci.crypt/msg/10a300c9d21afca0
26 #include "xyssl/config.h"
28 #if defined(XYSSL_ARC4_C)
30 #include "xyssl/arc4.h"
35 void arc4_setup( arc4_context
*ctx
, unsigned char *key
, int keylen
)
44 for( i
= 0; i
< 256; i
++ )
45 m
[i
] = (unsigned char) i
;
49 for( i
= 0; i
< 256; i
++, k
++ )
51 if( k
>= keylen
) k
= 0;
54 j
= ( j
+ a
+ key
[k
] ) & 0xFF;
56 m
[j
] = (unsigned char) a
;
61 * ARC4 cipher function
63 void arc4_crypt( arc4_context
*ctx
, unsigned char *buf
, int buflen
)
72 for( i
= 0; i
< buflen
; i
++ )
74 x
= ( x
+ 1 ) & 0xFF; a
= m
[x
];
75 y
= ( y
+ a
) & 0xFF; b
= m
[y
];
77 m
[x
] = (unsigned char) b
;
78 m
[y
] = (unsigned char) a
;
80 buf
[i
] = (unsigned char)
81 ( buf
[i
] ^ m
[(unsigned char)( a
+ b
)] );
88 #if defined(XYSSL_SELF_TEST)
94 * ARC4 tests vectors as posted by Eric Rescorla in sep. 1994:
96 * http://groups.google.com/group/comp.security.misc/msg/10a300c9d21afca0
98 static const unsigned char arc4_test_key
[3][8] =
100 { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
101 { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
102 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
105 static const unsigned char arc4_test_pt
[3][8] =
107 { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
108 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
109 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
112 static const unsigned char arc4_test_ct
[3][8] =
114 { 0x75, 0xB7, 0x87, 0x80, 0x99, 0xE0, 0xC5, 0x96 },
115 { 0x74, 0x94, 0xC2, 0xE7, 0x10, 0x4B, 0x08, 0x79 },
116 { 0xDE, 0x18, 0x89, 0x41, 0xA3, 0x37, 0x5D, 0x3A }
122 int arc4_self_test( int verbose
)
125 unsigned char buf
[8];
128 for( i
= 0; i
< 3; i
++ )
131 printf( " ARC4 test #%d: ", i
+ 1 );
133 memcpy( buf
, arc4_test_pt
[i
], 8 );
135 arc4_setup( &ctx
, (unsigned char *) arc4_test_key
[i
], 8 );
136 arc4_crypt( &ctx
, buf
, 8 );
138 if( memcmp( buf
, arc4_test_ct
[i
], 8 ) != 0 )
141 printf( "failed\n" );
147 printf( "passed\n" );