using OffsetArrays
mutable struct RC4
state::OffsetArray{UInt8}
i::UInt8
j::UInt8
RC4()=new(OffsetArray([ UInt8(i) for i in 0:255 ],-1),0,0)
end
function getRC4(k::OffsetArray{UInt8})
enc=RC4()
j::UInt8=0
for i=0:255
j+=enc.state[i]+k[i%length(k)]
enc.state[[i,j]]=enc.state[[j,i]]
end
enc
end
function getRC4(k::Array)
getRC4(OffsetArray(k,-1))
end
function getRC4(k::String)
getRC4(Array{UInt8}(k))
end
function getencryptor(enc::RC4)
function encode(c::Channel)
while true
enc.i+=1
enc.j+=enc.state[enc.i]
enc.state[[enc.i,enc.j]]=enc.state[[enc.j,enc.i]]
k=enc.state[enc.state[enc.i]+enc.state[enc.j]]
put!(c,k)
end
end
end
function encrypt(enc::RC4,text::Array{UInt8})
stream=Channel(getencryptor(enc))
String([ cā»take!(stream) for c in text])
end
function encrypt(enc::RC4,text::String)
encrypt(enc,Array{UInt8}(text))
end
M="This is a secret message which we want to encode"
cc=getRC4("Secret")
E=encrypt(cc,M)
cc=getRC4("Secret")
D=encrypt(cc,E)