forked from marcoskirsch/nodemcu-httpserver
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver-b64decode.lua
More file actions
Latest commit
executable file
·65 lines (57 loc) · 2.16 KB
/
Copy pathhttpserver-b64decode.lua
File metadata and controls
executable file
·65 lines (57 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/local/bin/lua
-- httpserver-b64decode.lua
-- Part of nodemcu-httpserver, contains b64 decoding used for HTTP Basic Authentication.
-- Based on http://lua-users.org/wiki/BaseSixtyFour by Alex Kloss
-- compatible with lua 5.1
-- http://www.it-rfc.de
-- Author: Marcos Kirsch
-- bitshift functions (<<, >> equivalent)
-- shift left
localfunctionlsh(value,shift)
return (value*(2^shift)) %256
end
-- shift right
localfunctionrsh(value,shift)
-- Lua builds with no floating point don't define math.
ifmaththenreturnmath.floor(value/2^shift) %256end
return (value/2^shift) %256
end
-- return single bit (for OR)
localfunctionbit(x,b)
return (x%2^b-x%2^(b-1) >0)
end
-- logic OR for number values
localfunctionlor(x,y)
result=0
forp=1,8doresult=result+ (((bit(x,p) orbit(y,p)) ==true) and2^(p-1) or0) end
returnresult
end
-- Character decoding table
localfunctiontoBase64Byte(char)
ascii=string.byte(char, 1)
ifascii>=string.byte('A', 1) andascii<=string.byte('Z', 1) thenreturnascii-string.byte('A', 1)
elseifascii>=string.byte('a', 1) andascii<=string.byte('z', 1) thenreturnascii-string.byte('a', 1) +26
elseifascii>=string.byte('0', 1) andascii<=string.byte('9', 1) thenreturnascii+4
elseifascii==string.byte('-', 1) thenreturn62
elseifascii==string.byte('_', 1) thenreturn63
elseifascii==string.byte('=', 1) thenreturnnil
elsereturnnil, "ERROR! Char is invalid for Base64 encoding: "..charend
end
-- decode base64 input to string
returnfunction(data)
localchars= {}
localresult=""
fordpos=0,string.len(data)-1,4do
forchar=1,4dochars[char] =toBase64Byte((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) andstring.char(lor(lsh(chars[2],4),
rsh(chars[3],2))) or"",
(chars[4] ~=nil) andstring.char(lor(lsh(chars[3],6) %192,
(chars[4]))) or""
)
end
returnresult
end