cfb.js 869 B

123456789101112131415161718192021222324252627282930313233
  1. var Buffer = require('safe-buffer').Buffer
  2. var xor = require('buffer-xor')
  3. function encryptStart (self, data, decrypt) {
  4. var len = data.length
  5. var out = xor(data, self._cache)
  6. self._cache = self._cache.slice(len)
  7. self._prev = Buffer.concat([self._prev, decrypt ? data : out])
  8. return out
  9. }
  10. exports.encrypt = function (self, data, decrypt) {
  11. var out = Buffer.allocUnsafe(0)
  12. var len
  13. while (data.length) {
  14. if (self._cache.length === 0) {
  15. self._cache = self._cipher.encryptBlock(self._prev)
  16. self._prev = Buffer.allocUnsafe(0)
  17. }
  18. if (self._cache.length <= data.length) {
  19. len = self._cache.length
  20. out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
  21. data = data.slice(len)
  22. } else {
  23. out = Buffer.concat([out, encryptStart(self, data, decrypt)])
  24. break
  25. }
  26. }
  27. return out
  28. }