#!/usr/bin/env python
 
import unicodedata
 
def ini_caja(clave):
    S = range(256)
    K = range(256)
    j = 0
    for i in range(256):
        if (j==len(clave)):
            j = 0
        K[i] = ord(clave[j])
        j = j+1
    
    j = 0
    for i in range(255):
        j = (j+S[i]+K[i])%256
        aux = S[i]
        S[i] = S[j]
        S[j] = aux
    
    return S
 
 
def rc4(nomfich, nomdest, clave):
    S = ini_caja(clave)
    dest = open(nomdest, 'w')
    data = open(nomfich, 'r')
    data.seek(0,2)
    tam = data.tell()
    data.seek(0,0)
    i, j = 0, 0
    while(data.tell() < tam):
        i = (i+1)%256
        j = (j+1)%256
        aux = S[i]
        S[i] = S[j]
        S[j] = aux
        t = (S[i] + S[j])%256
        O = S[t]
        b = data.read(1)
        w = O ^ ord(b)
        dest.write(chr(w))