FYI: base64 decode and encode in corona

It took me a long time to find this, since its not in the documentation, but fast base64 encode and decode are available via “mime” as part of the LuaSocket (socket.*) library.

local mime=require(“mime”)

mime.b64 for encode
mime.unb64 for decode

hope that helps someone! [import]uid: 122310 topic_id: 29710 reply_id: 329710[/import]

@aisaksen, if its not documented in corona API page its doesn’t mean you can’t use lua modules and functions available somewhere else, except for some lua functions.

I just mean the base64 encode and decode functions are already known to corona developers (at least i think so, lol) [import]uid: 147582 topic_id: 29710 reply_id: 119233[/import]

@aisaksen,

Thanks for the info, every bit helps.

You can also check out:
http://developer.coronalabs.com/code/how-upload-image-server-multipartform-data

The above combines it with a multi-part form submit to a server. [import]uid: 8045 topic_id: 29710 reply_id: 119244[/import]

be careful! the mime encoder and decoder have a nasty bug in LuaSocket 2.0.2 which causes them to give back bad data when encoding larger than 384 bytes

http://osdir.com/ml/lua@bazar2.conectiva.com.br/2010-03/msg00832.html

use this code instead:

[code]
function base64.encode(data)
local len = data:len()
local t = {}
for i=1,len,384 do
local n = math.min(384, len+1-i)
if n > 0 then
local s = data:sub(i, i+n-1)
local enc, _ = mime.b64(s)
t[#t+1] = enc
end
end

return table.concat(t)
end

function base64.decode(data)
local len = data:len()
local t = {}
for i=1,len,384 do
local n = math.min(384, len+1-i)
if n > 0 then
local s = data:sub(i, i+n-1)
local dec, _ = mime.unb64(s)
t[#t+1] = dec
end
end
return table.concat(t)
end
[/code] [import]uid: 122310 topic_id: 29710 reply_id: 119690[/import]

@aisaksen, thank you for sharing your finding. Bookmarked for future reference.

Naomi [import]uid: 67217 topic_id: 29710 reply_id: 119697[/import]

be careful! the mime encoder and decoder have a nasty bug in LuaSocket 2.0.2 which causes them to give back bad data when encoding larger than 384 bytes

http://osdir.com/ml/lua@bazar2.conectiva.com.br/2010-03/msg00832.html

use this code instead:

[code]
function base64.encode(data)
local len = data:len()
local t = {}
for i=1,len,384 do
local n = math.min(384, len+1-i)
if n > 0 then
local s = data:sub(i, i+n-1)
local enc, _ = mime.b64(s)
t[#t+1] = enc
end
end

return table.concat(t)
end

function base64.decode(data)
local len = data:len()
local t = {}
for i=1,len,384 do
local n = math.min(384, len+1-i)
if n > 0 then
local s = data:sub(i, i+n-1)
local dec, _ = mime.unb64(s)
t[#t+1] = dec
end
end
return table.concat(t)
end
[/code] [import]uid: 122310 topic_id: 29710 reply_id: 119690[/import]

@aisaksen, thank you for sharing your finding. Bookmarked for future reference.

Naomi [import]uid: 67217 topic_id: 29710 reply_id: 119697[/import]