Skip to content
This repository
Browse code

Fix for base64 decode handling bits of last octet

  • Loading branch information...
commit 4625c9dd7cd9feb5926637f1f43e57f2f5294ffc 1 parent 024f8db
Karthik Chokkaram authored June 14, 2011 probablycorey committed June 17, 2011
2  lib/stdlib/helpers/base64.lua
@@ -54,7 +54,7 @@ function decode(data)
54 54
     for char=1,4 do chars[char] = base64bytes[(string.sub(data,(dpos+char),(dpos+char)) or "=")] end
55 55
     result = result .. string.char(lor(lsh(chars[1],2), rsh(chars[2],4)))
56 56
     result = result .. ((chars[3] ~= nil) and string.char(lor(lsh(chars[2],4), rsh(chars[3],2))) or "")
57  
-    result = result .. ((chars[4] ~= nil) and string.char(lor(lsh(chars[3],6) % 192, (chars[4]))) or "")
  57
+    result = result .. ((chars[4] ~= nil) and string.char(lor(lsh(chars[3] % 4,6), (chars[4]))) or "")
58 58
   end
59 59
   return result
60 60
 end
36  tools/Tests/scripts/tests/base64Test.lua
... ...
@@ -1,4 +1,26 @@
1 1
 
  2
+describe["Base64 encoding"] = function()
  3
+  
  4
+  it["should be able to round trip tricky combinations of two bytes"] = function()
  5
+    for a = 0,255 do
  6
+      for _,b in ipairs({0,1,2,252,253,254}) do
  7
+        local s = string.char(a)..string.char(b)
  8
+        expect(wax.base64.decode(wax.base64.encode(s))).should_be(s)
  9
+      end
  10
+    end
  11
+  end
  12
+
  13
+  it["should get the same results as tclsh's base64"] = function()
  14
+    local data = string.char(unpack({
  15
+      0,16,131,16,81,135,32,146,139,48,211,143,65,20,147,81,
  16
+      85,151,97,150,155,113,215,159,130,24,163,146,89,167,162,154,
  17
+      171,178,219,175,195,28,179,211,93,183,227,158,187,243,223,191
  18
+    }))
  19
+    expect(wax.base64.encode(data)).should_be("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
  20
+  end
  21
+  
  22
+end
  23
+
2 24
 describe["Base64 decoding"] = function()
3 25
 
4 26
   it["should pass ASCII NULs"] = function()
@@ -8,4 +30,18 @@ describe["Base64 decoding"] = function()
8 30
     expect(string.byte(ans, 2)).should_be(0)
9 31
   end
10 32
 
  33
+  it["should get the same results as tclsh's base64"] = function()
  34
+    local data = string.char(unpack({
  35
+      0,16,131,16,81,135,32,146,139,48,211,143,65,20,147,81,
  36
+      85,151,97,150,155,113,215,159,130,24,163,146,89,167,162,154,
  37
+      171,178,219,175,195,28,179,211,93,183,227,158,187,243,223,191
  38
+    }))
  39
+    expect(wax.base64.decode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")).should_be(data)
  40
+  end
  41
+
  42
+  it["should handle the 254,0,0,0 scenario"] = function()
  43
+    local data = string.char(unpack({0,0,254}))
  44
+    expect(wax.base64.decode(wax.base64.encode(data))).should_be(data)
  45
+  end
  46
+
11 47
 end

0 notes on commit 4625c9d

Please sign in to comment.
Something went wrong with that request. Please try again.