test.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var test = require('tape')
  2. var DES = require('./')
  3. var modes = require('./modes')
  4. var crypto = require('crypto')
  5. Object.keys(modes).forEach(function (mode) {
  6. test(mode, function (t) {
  7. var i = 0
  8. while (++i < 10) {
  9. runOnce(i)
  10. }
  11. function runOnce (i) {
  12. t.test('run: ' + i, function (t) {
  13. t.plan(2)
  14. var key = crypto.randomBytes(modes[mode].key)
  15. var iv = crypto.randomBytes(modes[mode].iv)
  16. var text = crypto.randomBytes(200)
  17. var ourEncrypt
  18. try {
  19. ourEncrypt = new DES({
  20. mode: mode,
  21. key: key,
  22. iv: iv
  23. })
  24. } catch (e) {
  25. t.notOk(e, e.stack)
  26. }
  27. var nodeEncrypt
  28. try {
  29. nodeEncrypt = crypto.createCipheriv(mode, key, iv)
  30. } catch (e) {
  31. t.notOk(e, e.stack)
  32. }
  33. var ourCipherText = Buffer.concat([ourEncrypt.update(text), ourEncrypt.final()])
  34. var nodeCipherText = Buffer.concat([nodeEncrypt.update(text), nodeEncrypt.final()])
  35. t.equals(nodeCipherText.toString('hex'), ourCipherText.toString('hex'))
  36. var ourDecrypt = new DES({
  37. mode: mode,
  38. key: key,
  39. iv: iv,
  40. decrypt: true
  41. })
  42. var plainText = Buffer.concat([ourDecrypt.update(ourCipherText), ourDecrypt.final()])
  43. t.equals(text.toString('hex'), plainText.toString('hex'))
  44. })
  45. }
  46. })
  47. })