Permalink
Browse files

Fix for base64 decode handling bits of last octet

  • Loading branch information...
1 parent 024f8db commit 4625c9dd7cd9feb5926637f1f43e57f2f5294ffc @Omniwheel Omniwheel committed with Jun 14, 2011
Showing with 37 additions and 1 deletion.
  1. +1 −1 lib/stdlib/helpers/base64.lua
  2. +36 −0 tools/Tests/scripts/tests/base64Test.lua
View
2 lib/stdlib/helpers/base64.lua
@@ -54,7 +54,7 @@ function decode(data)
for char=1,4 do chars[char] = base64bytes[(string.sub(data,(dpos+char),(dpos+char)) or "=")] end
result = result .. string.char(lor(lsh(chars[1],2), rsh(chars[2],4)))
result = result .. ((chars[3] ~= nil) and string.char(lor(lsh(chars[2],4), rsh(chars[3],2))) or "")
- result = result .. ((chars[4] ~= nil) and string.char(lor(lsh(chars[3],6) % 192, (chars[4]))) or "")
+ result = result .. ((chars[4] ~= nil) and string.char(lor(lsh(chars[3] % 4,6), (chars[4]))) or "")
end
return result
end
View
36 tools/Tests/scripts/tests/base64Test.lua
@@ -1,4 +1,26 @@
+describe["Base64 encoding"] = function()
+
+ it["should be able to round trip tricky combinations of two bytes"] = function()
+ for a = 0,255 do
+ for _,b in ipairs({0,1,2,252,253,254}) do
+ local s = string.char(a)..string.char(b)
+ expect(wax.base64.decode(wax.base64.encode(s))).should_be(s)
+ end
+ end
+ end
+
+ it["should get the same results as tclsh's base64"] = function()
+ local data = string.char(unpack({
+ 0,16,131,16,81,135,32,146,139,48,211,143,65,20,147,81,
+ 85,151,97,150,155,113,215,159,130,24,163,146,89,167,162,154,
+ 171,178,219,175,195,28,179,211,93,183,227,158,187,243,223,191
+ }))
+ expect(wax.base64.encode(data)).should_be("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
+ end
+
+end
+
describe["Base64 decoding"] = function()
it["should pass ASCII NULs"] = function()
@@ -8,4 +30,18 @@ describe["Base64 decoding"] = function()
expect(string.byte(ans, 2)).should_be(0)
end
+ it["should get the same results as tclsh's base64"] = function()
+ local data = string.char(unpack({
+ 0,16,131,16,81,135,32,146,139,48,211,143,65,20,147,81,
+ 85,151,97,150,155,113,215,159,130,24,163,146,89,167,162,154,
+ 171,178,219,175,195,28,179,211,93,183,227,158,187,243,223,191
+ }))
+ expect(wax.base64.decode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")).should_be(data)
+ end
+
+ it["should handle the 254,0,0,0 scenario"] = function()
+ local data = string.char(unpack({0,0,254}))
+ expect(wax.base64.decode(wax.base64.encode(data))).should_be(data)
+ end
+
end

0 comments on commit 4625c9d

Please sign in to comment.