Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

test.js 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. t.test('run text: ' + i, function (t) {
  46. t.plan(2)
  47. var key = crypto.randomBytes(32).toString('base64').slice(0, modes[mode].key)
  48. var iv = crypto.randomBytes(32).toString('base64').slice(0, modes[mode].iv)
  49. var text = crypto.randomBytes(200)
  50. var ourEncrypt
  51. try {
  52. ourEncrypt = new DES({
  53. mode: mode,
  54. key: key,
  55. iv: iv
  56. })
  57. } catch (e) {
  58. t.notOk(e, e.stack)
  59. }
  60. var nodeEncrypt
  61. try {
  62. nodeEncrypt = crypto.createCipheriv(mode, key, iv)
  63. } catch (e) {
  64. t.notOk(e, e.stack)
  65. }
  66. var ourCipherText = Buffer.concat([ourEncrypt.update(text), ourEncrypt.final()])
  67. var nodeCipherText = Buffer.concat([nodeEncrypt.update(text), nodeEncrypt.final()])
  68. t.equals(nodeCipherText.toString('hex'), ourCipherText.toString('hex'))
  69. var ourDecrypt = new DES({
  70. mode: mode,
  71. key: key,
  72. iv: iv,
  73. decrypt: true
  74. })
  75. var plainText = Buffer.concat([ourDecrypt.update(ourCipherText), ourDecrypt.final()])
  76. t.equals(text.toString('hex'), plainText.toString('hex'))
  77. })
  78. }
  79. })
  80. })