0

I am learning base64 conversion into lua from enter link description here . Why i am getting error

2013/12/02 04:46:06 [error] 6493#0: *1 lua entry thread aborted: runtime error: /home/django/core/lua/redis_cache.lua:34: attempt to perform arithmetic on local 'value' (a nil value)

My .lua file

local data, err = red:get('session:' .. sessionid)
ngx.log(ngx.ALERT, data)

local function lsh(value,shift)
        return (value*(2^shift)) % 256
end

function rsh(value,shift)
        return math.floor(value/2^shift) % 256
end

function bit(x,b)
        return (x % 2^b - x % 2^(b-1) > 0)
end


function lor(x,y)
        result = 0
        for p=1,8 do result = result + (((bit(x,p) or bit(y,p)) == true) and 2^(p-1) or 0) end
        return result
end


local base64bytes = {['A']=0,['B']=1,['C']=2,['D']=3,['E']=4,['F']=5,['G']=6,['H']=7,['I']=8,['J']=9,['K']=10,['L']=11,['M']=12,['N']=13,['O']=14,['P']=15,['Q']=16,['R']=17,['S']=18,['T']=19,['U']=20,['V']=21,['W']=22,['X']=23,['Y']=24,['Z']=25,['a']=26,['b']=27,['c']=28,['d']=29,['e']=30,['f']=31,['g']=32,['h']=33,['i']=34,['j']=35,['k']=36,['l']=37,['m']=38,['n']=39,['o']=40,['p']=41,['q']=42,['r']=43,['s']=44,['t']=45,['u']=46,['v']=47,['w']=48,['x']=49,['y']=50,['z']=51,['0']=52,['1']=53,['2']=54,['3']=55,['4']=56,['5']=57,['6']=58,['7']=59,['8']=60,['9']=61,['-']=62,['_']=63,['=']=nil}

local function dec(data)
        local chars = {}
        local result=""
        for dpos=0,string.len(data)-1,4 do
                for char=1,4 do chars[char] = base64bytes[(string.sub(data,(dpos+char),(dpos+char)) or "=")] end
                result = string.format('%s%s%s%s',result,string.char(lor(lsh(chars[1],2), rsh(chars[2],4))),(chars[3] ~= nil) and string.char(lor(lsh(chars[2],4), rsh(chars[3],2))) or "",(chars[4] ~= nil) and string.char(lor(lsh(chars[3],6) % 192, (chars[4]))) or "")
        end
        return result
end


ngx.say(dec(data))

1 Answer 1

4

Your algorithm is failing for every data of length 4n+1 because you are not checking if the 2nd character in the loop is nil. To fix this, you will need to add a check similar to the ones you already have for chars[3] and chars[4].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.