From cef1e48b12b69af4d15db609b3d0db3a7d5bde67 Mon Sep 17 00:00:00 2001 From: Philipp von Weitershausen Date: Fri, 17 Sep 2010 17:48:06 +0200 Subject: [PATCH] Bug 593820 - Move generatePassphrase and friends from UI code to util.js [r=mconnor] --- services/sync/modules/util.js | 31 +++++++++++++++++++ .../sync/tests/unit/test_utils_passphrase.js | 25 +++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 services/sync/tests/unit/test_utils_passphrase.js diff --git a/services/sync/modules/util.js b/services/sync/modules/util.js index 052868baa3e2..922bb6e8c8fb 100644 --- a/services/sync/modules/util.js +++ b/services/sync/modules/util.js @@ -830,6 +830,37 @@ let Utils = { } }, + /** + * Generate 20 random characters a-z + */ + generatePassphrase: function() { + let rng = Cc["@mozilla.org/security/random-generator;1"] + .createInstance(Ci.nsIRandomGenerator); + let bytes = rng.generateRandomBytes(20); + return [String.fromCharCode(97 + Math.floor(byte * 26 / 256)) + for each (byte in bytes)].join(""); + }, + + /** + * Hyphenate a 20 character passphrase in 4 groups of 5. + */ + hyphenatePassphrase: function(passphrase) { + return passphrase.slice(0, 5) + '-' + + passphrase.slice(5, 10) + '-' + + passphrase.slice(10, 15) + '-' + + passphrase.slice(15, 20); + }, + + /** + * Remove hyphens as inserted by hyphenatePassphrase(). + */ + normalizePassphrase: function(pp) { + if (pp.length == 23 && pp[5] == '-' && pp[11] == '-' && pp[17] == '-') + return pp.slice(0, 5) + pp.slice(6, 11) + + pp.slice(12, 17) + pp.slice(18, 23); + return pp; + }, + /** * Create an array like the first but without elements of the second */ diff --git a/services/sync/tests/unit/test_utils_passphrase.js b/services/sync/tests/unit/test_utils_passphrase.js new file mode 100644 index 000000000000..f0ef5dee7375 --- /dev/null +++ b/services/sync/tests/unit/test_utils_passphrase.js @@ -0,0 +1,25 @@ +Cu.import("resource://services-sync/util.js"); + +function run_test() { + _("Generated passphrase has length 20."); + let pp = Utils.generatePassphrase(); + do_check_eq(pp.length, 20); + + _("Passphrase only contains a-z."); + let bytes = [chr.charCodeAt() for each (chr in pp)]; + do_check_true(Math.min.apply(null, bytes) >= 97); + do_check_true(Math.max.apply(null, bytes) <= 122); + + _("Hyphenated passphrase has 3 hyphens."); + let hyphenated = Utils.hyphenatePassphrase(pp); + do_check_eq(hyphenated.length, 23); + do_check_eq(hyphenated[5], '-'); + do_check_eq(hyphenated[11], '-'); + do_check_eq(hyphenated[17], '-'); + do_check_eq(hyphenated.slice(0, 5) + hyphenated.slice(6, 11) + + hyphenated.slice(12, 17) + hyphenated.slice(18, 23), pp); + + _("Normalize passphrase recognizes hyphens."); + do_check_eq(Utils.normalizePassphrase(hyphenated), pp); + do_check_eq(pp, pp); +}