arc4.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 FILE_LICENCE ( GPL2_OR_LATER );
00022
00023 #include <gpxe/crypto.h>
00024 #include <gpxe/arc4.h>
00025
00026 #define SWAP( ary, i, j ) \
00027 ({ u8 temp = ary[i]; ary[i] = ary[j]; ary[j] = temp; })
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041 static int arc4_setkey ( void *ctxv, const void *keyv, size_t keylen )
00042 {
00043 struct arc4_ctx *ctx = ctxv;
00044 const u8 *key = keyv;
00045 u8 *S = ctx->state;
00046 int i, j;
00047
00048 for ( i = 0; i < 256; i++ ) {
00049 S[i] = i;
00050 }
00051
00052 for ( i = j = 0; i < 256; i++ ) {
00053 j = ( j + S[i] + key[i % keylen] ) & 0xff;
00054 SWAP ( S, i, j );
00055 }
00056
00057 ctx->i = ctx->j = 0;
00058 return 0;
00059 }
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077 static void arc4_xor ( void *ctxv, const void *srcv, void *dstv,
00078 size_t len )
00079 {
00080 struct arc4_ctx *ctx = ctxv;
00081 const u8 *src = srcv;
00082 u8 *dst = dstv;
00083 u8 *S = ctx->state;
00084 int i = ctx->i, j = ctx->j;
00085
00086 while ( len-- ) {
00087 i = ( i + 1 ) & 0xff;
00088 j = ( j + S[i] ) & 0xff;
00089 SWAP ( S, i, j );
00090 if ( srcv && dstv )
00091 *dst++ = *src++ ^ S[(S[i] + S[j]) & 0xff];
00092 }
00093
00094 ctx->i = i;
00095 ctx->j = j;
00096 }
00097
00098 static void arc4_setiv ( void *ctx __unused, const void *iv __unused )
00099 {
00100
00101 }
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114 void arc4_skip ( const void *key, size_t keylen, size_t skip,
00115 const void *src, void *dst, size_t msglen )
00116 {
00117 struct arc4_ctx ctx;
00118 arc4_setkey ( &ctx, key, keylen );
00119 arc4_xor ( &ctx, NULL, NULL, skip );
00120 arc4_xor ( &ctx, src, dst, msglen );
00121 }
00122
00123 struct cipher_algorithm arc4_algorithm = {
00124 .name = "ARC4",
00125 .ctxsize = ARC4_CTX_SIZE,
00126 .blocksize = 1,
00127 .setkey = arc4_setkey,
00128 .setiv = arc4_setiv,
00129 .encrypt = arc4_xor,
00130 .decrypt = arc4_xor,
00131 };