test_secretbox.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * Created by bmf on 11/2/13.
  3. */
  4. var assert = require('assert');
  5. var sodium = require('../build/Release/sodium');
  6. var SecretBox = require('../lib/secretbox');
  7. if (process.env.COVERAGE) {
  8. SecretBox = require('../lib-cov/secretbox');
  9. }
  10. describe("SecretBox", function () {
  11. it("encrypt/decrypt and validate message", function (done) {
  12. var box = new SecretBox();
  13. box.setEncoding('utf8');
  14. var cipherBox = box.encrypt("This is a test");
  15. assert.equal(box.decrypt(cipherBox), "This is a test");
  16. done();
  17. });
  18. it("encrypt should return a valid cipherbox", function (done) {
  19. var box = new SecretBox();
  20. box.setEncoding('utf8');
  21. var cipherBox = box.encrypt("This is a test");
  22. assert.equal(typeof cipherBox, 'object');
  23. assert.notEqual(typeof cipherBox.cipherText, 'undefined');
  24. assert.notEqual(typeof cipherBox.nonce, 'undefined');
  25. assert.ok(cipherBox.cipherText instanceof Buffer);
  26. assert.ok(cipherBox.nonce instanceof Buffer);
  27. done();
  28. });
  29. it("key size should match that of sodium", function (done) {
  30. var box = new SecretBox();
  31. assert.equal(box.key().size(), sodium.crypto_secretbox_KEYBYTES);
  32. done();
  33. });
  34. it("generate throw on a bad cipherBox buffer", function (done) {
  35. var box = new SecretBox();
  36. var cipherBox = box.encrypt("This is a test", 'utf8');
  37. cipherBox.cipherText[0] = 99;
  38. cipherBox.cipherText[1] = 99;
  39. cipherBox.cipherText[2] = 99;
  40. assert.throws(function() {
  41. box.decrypt(cipherBox);
  42. });
  43. done();
  44. });
  45. it("generate return undefined on an altered cipherText", function (done) {
  46. var box = new SecretBox();
  47. var cipherBox = box.encrypt("This is a test", 'utf8');
  48. cipherBox.cipherText[18] = 99;
  49. cipherBox.cipherText[19] = 99;
  50. cipherBox.cipherText[20] = 99;
  51. var plainText = box.decrypt(cipherBox);
  52. if (!plainText) {
  53. done();
  54. }
  55. });
  56. it("set bad secretKey should fail", function (done) {
  57. var box = new SecretBox();
  58. assert.throws(function() {
  59. box.set(Buffer.allocUnsafe(2));
  60. });
  61. done();
  62. });
  63. it("set/get secretKey", function (done) {
  64. var box = new SecretBox();
  65. box.key().generate();
  66. var k = box.key().get();
  67. var auth2 = new SecretBox();
  68. auth2.key().set(k);
  69. k2 = auth2.key().get();
  70. assert.deepEqual(k2, k);
  71. done();
  72. });
  73. });