How to resolve the algorithm Base64 decode data step by step in the Lua programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Base64 decode data step by step in the Lua programming language

Table of Contents

Problem Statement

See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Base64 decode data step by step in the Lua programming language

Source code in the lua programming language

-- Start taken from https://stackoverflow.com/a/35303321
local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- You will need this for encoding/decoding

-- decoding
function dec(data)
    data = string.gsub(data, '[^'..b..'=]', '')
    return (data:gsub('.', function(x)
        if (x == '=') then return '' end
        local r,f='',(b:find(x)-1)
        for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
        return r;
    end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
        if (#x ~= 8) then return '' end
        local c=0
        for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
            return string.char(c)
    end))
end
-- end of copy

local data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"
print(data)
print()

local decoded = dec(data)
print(decoded)


  

You may also check:How to resolve the algorithm Fast Fourier transform step by step in the ooRexx programming language
You may also check:How to resolve the algorithm Equilibrium index step by step in the Swift programming language
You may also check:How to resolve the algorithm Video display modes step by step in the smart BASIC programming language
You may also check:How to resolve the algorithm Sierpinski triangle step by step in the Euphoria programming language
You may also check:How to resolve the algorithm Caesar cipher step by step in the ZX Spectrum Basic programming language