index.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var CipherBase = require('cipher-base')
  2. var des = require('des.js')
  3. var inherits = require('inherits')
  4. var Buffer = require('safe-buffer').Buffer
  5. var modes = {
  6. 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
  7. 'des-ede3': des.EDE,
  8. 'des-ede-cbc': des.CBC.instantiate(des.EDE),
  9. 'des-ede': des.EDE,
  10. 'des-cbc': des.CBC.instantiate(des.DES),
  11. 'des-ecb': des.DES
  12. }
  13. modes.des = modes['des-cbc']
  14. modes.des3 = modes['des-ede3-cbc']
  15. module.exports = DES
  16. inherits(DES, CipherBase)
  17. function DES (opts) {
  18. CipherBase.call(this)
  19. var modeName = opts.mode.toLowerCase()
  20. var mode = modes[modeName]
  21. var type
  22. if (opts.decrypt) {
  23. type = 'decrypt'
  24. } else {
  25. type = 'encrypt'
  26. }
  27. var key = opts.key
  28. if (!Buffer.isBuffer(key)) {
  29. key = Buffer.from(key)
  30. }
  31. if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
  32. key = Buffer.concat([key, key.slice(0, 8)])
  33. }
  34. var iv = opts.iv
  35. if (!Buffer.isBuffer(iv)) {
  36. iv = Buffer.from(iv)
  37. }
  38. this._des = mode.create({
  39. key: key,
  40. iv: iv,
  41. type: type
  42. })
  43. }
  44. DES.prototype._update = function (data) {
  45. return Buffer.from(this._des.update(data))
  46. }
  47. DES.prototype._final = function () {
  48. return Buffer.from(this._des.final())
  49. }