Bug 760105 - Add argument to CommonUtils.encodeBase64URL for padding; r=rnewman

This commit is contained in:
Gregory Szorc 2012-06-01 15:12:37 +02:00
parent 232a8ee6a3
commit dd9fa06556
3 changed files with 43 additions and 3 deletions

View File

@ -0,0 +1,27 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://services-common/utils.js");
function run_test() {
run_next_test();
}
add_test(function test_simple() {
let expected = {
hello: "aGVsbG8=",
"<>?": "PD4_",
};
for (let [k, v] in Iterator(expected)) {
do_check_eq(CommonUtils.encodeBase64URL(k), v);
}
run_next_test();
});
add_test(function test_no_padding() {
do_check_eq(CommonUtils.encodeBase64URL("hello", false), "aGVsbG8");
run_next_test();
});

View File

@ -7,6 +7,7 @@ tail =
[test_utils_atob.js]
[test_utils_encodeBase32.js]
[test_utils_encodeBase64URL.js]
[test_utils_json.js]
[test_utils_makeURI.js]
[test_utils_namedTimer.js]

View File

@ -59,11 +59,23 @@ let CommonUtils = {
/**
* Encode byte string as base64URL (RFC 4648).
*
* @param bytes
* (string) Raw byte string to encode.
* @param pad
* (bool) Whether to include padding characters (=). Defaults
* to true for historical reasons.
*/
encodeBase64URL: function encodeBase64URL(bytes) {
return btoa(bytes).replace("+", "-", "g").replace("/", "_", "g");
encodeBase64URL: function encodeBase64URL(bytes, pad=true) {
let s = btoa(bytes).replace("+", "-", "g").replace("/", "_", "g");
if (!pad) {
s = s.replace("=", "");
}
return s;
},
/**
* Create a nsIURI instance from a string.
*/