jooking / closure-library

Automatically exported from code.google.com/p/closure-library
Apache License 2.0
0 stars 1 forks source link

goog.crypt.base64.decodeStringToByteArray adds null bytes if length isn't a multiple of 4. #626

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

goog.crypt.base64.decodeStringToByteArray("QQ")

Expected: [65]
Actual: [65, 0, 0]

Note that:
1. goog.crypt.base64.decodeStringToByteArray("QQ==") correctly returns [65] and 
the method comment clearly states "length not required to be a multiple of 4".
2. On browsers with atob() defined, goog.crypt.base64.decodeString() will 
correctly decode "QQ" to "A" but without atob() defined, it hits the bad 
codepath and returns "A\u0000\u0000" instead.

The easy fix is to replace ": 0" with ": 64" in the following lines:

    var haveByte2 = i < input.length;
    var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
    ++i;

    var haveByte3 = i < input.length;
    var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 0;
    ++i;

    var haveByte4 = i < input.length;
    var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 0;
    ++i;

This works, since '=' decodes to 64 and 64 as treated as "nothing" in the 
subsequent code.

Original issue reported on code.google.com by mich...@firebase.com on 4 Feb 2014 at 12:18