VMPC stream cipher implement in Lua


VMPC (Variably Modified Permutation Composition) is a stream cipher similar to the well known and popular cipher RC4 designed by Ron Rivest. It was designed by Bartosz Zoltak, presented in 2004 at the Fast Software Encryption conference. VMPC is a modification of the RC4 cipher.

We provided some function of VMPC stream cipher implement in PHP and Javascript here: VMPC stream cipher implement in PHP and Javascript

Now we provide VMPC stream cipher implement in Lua:

local function vmpc(t, e) 
  local i, n, r, a, s, o, v, k = {},0,nil,""
  for s = 0, 255 do i[s+1] = s end
  for k = 1, 3 do  
    for s = 1,256 do
      n = (n + i[s] + string.byte(e, 1+(s-1) % #e) ) % 256
      r = i[s]
      i[s] = i[n+1]
      i[n+1] = r
    end
  end

  s = 1
  n = 0
  r = 0
  for o=1,#t do
    r = i[s]
    n = i[(n + r) % 256+1]
    a = a .. string.char(bxor(string.byte(t,o) , i[i[(i[n+1]+1) % 256+1]+1]))
    r = i[s]
    i[s] = i[n+1]
    i[n+1] = r
    s = s % 256 + 1
  end
  return a
end

Note: Lua: bitwise xor for Lua < 5.2

Example:

local a = "tutorialspots.com"

local b = vmpc(a,a) -- ˜Q~SõÇ­/VœÎ)¾

a = vmpc(b,a) -- tutorialspots.com

print(b)

Second method:

local function vmpc2(t, e) 
  local i, n, r, a, s, o, v, k = {},0,nil,""
  for s = 0, 255 do i[s+1] = s end
  for k = 1, 3 do  
    for s = 1,256 do
      n = (n + i[s] + string.byte(e, 1+(s-1) % #e) ) % 256
      r = i[s]
      i[s] = i[n+1]
      i[n+1] = r
    end
  end

  s = 1
  n = 0
  r = 0
  for o=1,#t do
    r = i[s]
    n = i[(n + r) % 256+1]
    a = a .. string.char(bxor(string.byte(t,o) , i[i[(i[n+1]+1) % 256 +1]+1]))
    r = i[s]
    i[s] = i[n+1]
    i[n+1] = r
    s = s % 256 + 1
  end
  return a
end

Leave a Reply