summaryrefslogtreecommitdiffstats
path: root/services/crypto/tests/unit/test_crypto_random.js
blob: 46b4c7f82f48c7f1e1a96972a3ac73414f30f579 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var WeaveCryptoModule = Cu.import("resource://services-crypto/WeaveCrypto.js");

var cryptoSvc = new WeaveCrypto();

function run_test() {
  if (this.gczeal) {
    _("Running crypto random tests with gczeal(2).");
    gczeal(2);
  }

  // Test salt generation.
  var salt;

  salt = cryptoSvc.generateRandomBytes(0);
  do_check_eq(salt.length, 0);
  salt = cryptoSvc.generateRandomBytes(1);
  do_check_eq(salt.length, 4);
  salt = cryptoSvc.generateRandomBytes(2);
  do_check_eq(salt.length, 4);
  salt = cryptoSvc.generateRandomBytes(3);
  do_check_eq(salt.length, 4);
  salt = cryptoSvc.generateRandomBytes(4);
  do_check_eq(salt.length, 8);
  salt = cryptoSvc.generateRandomBytes(8);
  do_check_eq(salt.length, 12);

  // sanity check to make sure salts seem random
  var salt2 = cryptoSvc.generateRandomBytes(8);
  do_check_eq(salt2.length, 12);
  do_check_neq(salt, salt2);

  salt = cryptoSvc.generateRandomBytes(1024);
  do_check_eq(salt.length, 1368);
  salt = cryptoSvc.generateRandomBytes(16);
  do_check_eq(salt.length, 24);


  // Test random key generation
  var keydata, keydata2, iv;

  keydata  = cryptoSvc.generateRandomKey();
  do_check_eq(keydata.length, 44);
  keydata2 = cryptoSvc.generateRandomKey();
  do_check_neq(keydata, keydata2); // sanity check for randomness
  iv = cryptoSvc.generateRandomIV();
  do_check_eq(iv.length, 24);

  cryptoSvc.algorithm = WeaveCryptoModule.AES_256_CBC;
  keydata  = cryptoSvc.generateRandomKey();
  do_check_eq(keydata.length, 44);
  keydata2 = cryptoSvc.generateRandomKey();
  do_check_neq(keydata, keydata2); // sanity check for randomness
  iv = cryptoSvc.generateRandomIV();
  do_check_eq(iv.length, 24);

  if (this.gczeal)
    gczeal(0);
}