/* This code illustrates a sample implementation1* of the Arcfour algorithm2* Copyright (c) April 29, 1997 Kalle Kaukonen.3* All Rights Reserved.4*5* Redistribution and use in source and binary forms, with or6* without modification, are permitted provided that this copyright7* notice and disclaimer are retained.8*9* THIS SOFTWARE IS PROVIDED BY KALLE KAUKONEN AND CONTRIBUTORS ``AS10* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT11* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS12* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KALLE13* KAUKONEN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,14* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES15* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS16* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS17* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,18* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING19* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF20* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.21*/2223#include "mupdf/fitz.h"2425void26fz_arc4_init(fz_arc4 *arc4, const unsigned char *key, unsigned keylen)27{28unsigned int t, u;29unsigned int keyindex;30unsigned int stateindex;31unsigned char *state;32unsigned int counter;3334state = arc4->state;3536arc4->x = 0;37arc4->y = 0;3839for (counter = 0; counter < 256; counter++)40{41state[counter] = counter;42}4344keyindex = 0;45stateindex = 0;4647for (counter = 0; counter < 256; counter++)48{49t = state[counter];50stateindex = (stateindex + key[keyindex] + t) & 0xff;51u = state[stateindex];5253state[stateindex] = t;54state[counter] = u;5556if (++keyindex >= keylen)57{58keyindex = 0;59}60}61}6263static unsigned char64fz_arc4_next(fz_arc4 *arc4)65{66unsigned int x;67unsigned int y;68unsigned int sx, sy;69unsigned char *state;7071state = arc4->state;7273x = (arc4->x + 1) & 0xff;74sx = state[x];75y = (sx + arc4->y) & 0xff;76sy = state[y];7778arc4->x = x;79arc4->y = y;8081state[y] = sx;82state[x] = sy;8384return state[(sx + sy) & 0xff];85}8687void88fz_arc4_encrypt(fz_arc4 *arc4, unsigned char *dest, const unsigned char *src, unsigned len)89{90unsigned int i;91for (i = 0; i < len; i++)92{93unsigned char x;94x = fz_arc4_next(arc4);95dest[i] = src[i] ^ x;96}97}9899100