00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029 #ifndef _CRT_SECURE_NO_DEPRECATE
00030 #define _CRT_SECURE_NO_DEPRECATE 1
00031 #endif
00032
00033 #include "xyssl/arc4.h"
00034
00035
00036
00037
00038 void arc4_setup( arc4_context *ctx, unsigned char *key, int keylen )
00039 {
00040 int i, j, k, *m, a;
00041
00042 ctx->x = 0;
00043 ctx->y = 0;
00044 m = ctx->m;
00045
00046 for( i = 0; i < 256; i++ )
00047 m[i] = i;
00048
00049 j = k = 0;
00050
00051 for( i = 0; i < 256; i++ )
00052 {
00053 a = m[i];
00054 j = (unsigned char)( j + a + key[k] );
00055 m[i] = m[j]; m[j] = a;
00056 if( ++k >= keylen ) k = 0;
00057 }
00058 }
00059
00060
00061
00062
00063 void arc4_crypt( arc4_context *ctx, unsigned char *buf, int buflen )
00064 {
00065 int i, x, y, *m, a, b;
00066
00067 x = ctx->x;
00068 y = ctx->y;
00069 m = ctx->m;
00070
00071 for( i = 0; i < buflen; i++ )
00072 {
00073 x = (unsigned char)( x + 1 ); a = m[x];
00074 y = (unsigned char)( y + a );
00075 m[x] = b = m[y];
00076 m[y] = a;
00077 buf[i] ^= m[(unsigned char)( a + b )];
00078 }
00079
00080 ctx->x = x;
00081 ctx->y = y;
00082 }
00083
00084 static const char _arc4_src[] = "_arc4_src";
00085
00086 #if defined(SELF_TEST)
00087
00088 #include <string.h>
00089 #include <stdio.h>
00090
00091
00092
00093
00094 static const unsigned char arc4_test_key[3][8] =
00095 {
00096 { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
00097 { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
00098 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
00099 };
00100
00101 static const unsigned char arc4_test_pt[3][8] =
00102 {
00103 { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
00104 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
00105 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
00106 };
00107
00108 static const unsigned char arc4_test_ct[3][8] =
00109 {
00110 { 0x75, 0xB7, 0x87, 0x80, 0x99, 0xE0, 0xC5, 0x96 },
00111 { 0x74, 0x94, 0xC2, 0xE7, 0x10, 0x4B, 0x08, 0x79 },
00112 { 0xDE, 0x18, 0x89, 0x41, 0xA3, 0x37, 0x5D, 0x3A }
00113 };
00114
00115
00116
00117
00118 int arc4_self_test( int verbose )
00119 {
00120 int i;
00121 unsigned char buf[8];
00122 arc4_context ctx;
00123
00124 for( i = 0; i < 3; i++ )
00125 {
00126 if( verbose != 0 )
00127 printf( " ARC4 test #%d: ", i + 1 );
00128
00129 memcpy( buf, arc4_test_pt[i], 8 );
00130
00131 arc4_setup( &ctx, (unsigned char *) arc4_test_key[i], 8 );
00132 arc4_crypt( &ctx, buf, 8 );
00133
00134 if( memcmp( buf, arc4_test_ct[i], 8 ) != 0 )
00135 {
00136 if( verbose != 0 )
00137 printf( "failed\n" );
00138
00139 return( 1 );
00140 }
00141
00142 if( verbose != 0 )
00143 printf( "passed\n" );
00144 }
00145
00146 if( verbose != 0 )
00147 printf( "\n" );
00148
00149 return( 0 );
00150 }
00151 #else
00152 int arc4_self_test( int verbose )
00153 {
00154 return( 0 );
00155 }
00156 #endif