test.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var test = require('tape')
  2. var crypto = require('crypto')
  3. var desModes = require('browserify-des/modes')
  4. var aesModes = require('browserify-aes/modes')
  5. var ourCrypto = require('./browser')
  6. function runIvTest (mode, keyLen, ivLen) {
  7. test('mode: ' + mode, function (t) {
  8. var i = 0
  9. while (++i < 10) {
  10. run(i)
  11. }
  12. function run (i) {
  13. t.test('run: ' + i, function (t) {
  14. t.plan(2)
  15. var key = crypto.randomBytes(keyLen)
  16. var iv = crypto.randomBytes(ivLen)
  17. var text = crypto.randomBytes(200)
  18. var ourEncrypt
  19. try {
  20. ourEncrypt = ourCrypto.createCipheriv(mode, key, iv)
  21. } catch (e) {
  22. t.notOk(e, e.stack)
  23. }
  24. var nodeEncrypt
  25. try {
  26. nodeEncrypt = crypto.createCipheriv(mode, key, iv)
  27. } catch (e) {
  28. t.notOk(e, e.stack)
  29. }
  30. var ourCipherText = Buffer.concat([ourEncrypt.update(text), ourEncrypt.final()])
  31. var authTag
  32. if (mode.slice(-3) === 'gcm') {
  33. authTag = ourEncrypt.getAuthTag()
  34. }
  35. var nodeCipherText = Buffer.concat([nodeEncrypt.update(text), nodeEncrypt.final()])
  36. t.equals(nodeCipherText.toString('hex'), ourCipherText.toString('hex'))
  37. var ourDecrypt = ourCrypto.createDecipheriv(mode, key, iv)
  38. if (mode.slice(-3) === 'gcm') {
  39. ourDecrypt.setAuthTag(authTag)
  40. }
  41. var plainText = Buffer.concat([ourDecrypt.update(ourCipherText), ourDecrypt.final()])
  42. t.equals(text.toString('hex'), plainText.toString('hex'))
  43. })
  44. }
  45. })
  46. }
  47. Object.keys(aesModes).forEach(function (modeName) {
  48. var mode = aesModes[modeName]
  49. runIvTest(modeName, mode.key / 8, mode.iv)
  50. })
  51. Object.keys(desModes).forEach(function (modeName) {
  52. var mode = desModes[modeName]
  53. runIvTest(modeName, mode.key, mode.iv)
  54. })