test_sodium_algos_auth.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Created by bmf on 10/31/13.
  3. */
  4. "use strict";
  5. var assert = require('assert');
  6. var crypto = require('crypto');
  7. var sodium = require('../build/Release/sodium');
  8. var toBuffer = require('../lib/toBuffer');
  9. var key = Buffer.allocUnsafe(sodium.crypto_auth_KEYBYTES);
  10. key.fill('Jefe');
  11. key.fill(0, 4, 32);
  12. var c = toBuffer('what do ya want for nothing?', 'ascii');
  13. var key2 = toBuffer('Another one got caught today, it\'s all over the papers. "Teenager Arrested in Computer Crime Scandal", "Hacker Arrested after Bank Tampering"... Damn kids. They\'re all alike.', 'ascii');
  14. testAlgorithm('hmacsha256', key);
  15. testAlgorithm('hmacsha512', key);
  16. testAlgorithm('hmacsha512256', key);
  17. /* TESTS DISABLED DUE TO LIBSODIUM BUG.
  18. testAlgorithm('hmacsha256', key2);
  19. testAlgorithm('hmacsha512', key2);
  20. testAlgorithm('hmacsha512256', key2);
  21. */
  22. function testAlgorithm(algo, k) {
  23. // Split the message in half
  24. var halfLength = Math.ceil(c.length / 2);
  25. var c1 = c.slice(0, halfLength);
  26. var c2 = c.slice(halfLength, c.length);
  27. // Stream API
  28. var s1 = sodium['crypto_auth_' + algo + '_init'](k);
  29. var s2 = sodium['crypto_auth_' + algo + '_update'](s1, c1);
  30. var s3 = sodium['crypto_auth_' + algo + '_update'](s2, c2);
  31. var a1 = sodium['crypto_auth_' + algo + '_final'](s3);
  32. // Regular API
  33. var a2 = sodium['crypto_auth_' + algo](c, k);
  34. describe('LibSodium Auth, with key length ' + k.length, function() {
  35. it('Streamming API state is updating', function(done){
  36. // Assert that the states changed with each update
  37. assert.notDeepEqual(s1, s2);
  38. assert.notDeepEqual(s2, s3);
  39. assert.notDeepEqual(s1, s3);
  40. done();
  41. });
  42. it('Stream API must produce same results as regular API ' + algo, function(done) {
  43. // Assert that streamming API produces the same result as regular API
  44. assert(sodium.compare(a1, a2)==0, "Stream differs from Regular API" );
  45. done();
  46. });
  47. it('Token lengths must be what we expect for ' + algo, function(done) {
  48. // Is it the right token length
  49. assert.equal(a1.length, sodium['crypto_auth_' + algo + '_BYTES']);
  50. assert.equal(a2.length, sodium['crypto_auth_' + algo + '_BYTES']);
  51. done();
  52. });
  53. it('must verify auth token ' + algo, function(done) {
  54. assert.equal(sodium['crypto_auth_' + algo + '_verify'](a1, c, k), 0);
  55. assert.equal(sodium['crypto_auth_' + algo + '_verify'](a2, c, k), 0);
  56. done();
  57. });
  58. });
  59. }