ctr.js 908 B

123456789101112131415161718192021222324252627282930
  1. var xor = require('buffer-xor')
  2. var Buffer = require('safe-buffer').Buffer
  3. var incr32 = require('../incr32')
  4. function getBlock (self) {
  5. var out = self._cipher.encryptBlockRaw(self._prev)
  6. incr32(self._prev)
  7. return out
  8. }
  9. var blockSize = 16
  10. exports.encrypt = function (self, chunk) {
  11. var chunkNum = Math.ceil(chunk.length / blockSize)
  12. var start = self._cache.length
  13. self._cache = Buffer.concat([
  14. self._cache,
  15. Buffer.allocUnsafe(chunkNum * blockSize)
  16. ])
  17. for (var i = 0; i < chunkNum; i++) {
  18. var out = getBlock(self)
  19. var offset = start + i * blockSize
  20. self._cache.writeUInt32BE(out[0], offset + 0)
  21. self._cache.writeUInt32BE(out[1], offset + 4)
  22. self._cache.writeUInt32BE(out[2], offset + 8)
  23. self._cache.writeUInt32BE(out[3], offset + 12)
  24. }
  25. var pad = self._cache.slice(0, chunk.length)
  26. self._cache = self._cache.slice(chunk.length)
  27. return xor(chunk, pad)
  28. }