react / wstein / node_modules / browserify / node_modules / crypto-browserify / node_modules / browserify-aes / authCipher.js
80542 viewsvar aes = require('./aes')1var Transform = require('./cipherBase')2var inherits = require('inherits')3var GHASH = require('./ghash')4var xor = require('./xor')5inherits(StreamCipher, Transform)6module.exports = StreamCipher78function StreamCipher (mode, key, iv, decrypt) {9if (!(this instanceof StreamCipher)) {10return new StreamCipher(mode, key, iv)11}12Transform.call(this)13this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])])14iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])])15this._cipher = new aes.AES(key)16this._prev = new Buffer(iv.length)17this._cache = new Buffer('')18this._secCache = new Buffer('')19this._decrypt = decrypt20this._alen = 021this._len = 022iv.copy(this._prev)23this._mode = mode24var h = new Buffer(4)25h.fill(0)26this._ghash = new GHASH(this._cipher.encryptBlock(h))27this._authTag = null28this._called = false29}30StreamCipher.prototype._update = function (chunk) {31if (!this._called && this._alen) {32var rump = 16 - (this._alen % 16)33if (rump < 16) {34rump = new Buffer(rump)35rump.fill(0)36this._ghash.update(rump)37}38}39this._called = true40var out = this._mode.encrypt(this, chunk)41if (this._decrypt) {42this._ghash.update(chunk)43} else {44this._ghash.update(out)45}46this._len += chunk.length47return out48}49StreamCipher.prototype._final = function () {50if (this._decrypt && !this._authTag) {51throw new Error('Unsupported state or unable to authenticate data')52}53var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))54if (this._decrypt) {55if (xorTest(tag, this._authTag)) {56throw new Error('Unsupported state or unable to authenticate data')57}58} else {59this._authTag = tag60}61this._cipher.scrub()62}63StreamCipher.prototype.getAuthTag = function getAuthTag () {64if (!this._decrypt && Buffer.isBuffer(this._authTag)) {65return this._authTag66} else {67throw new Error('Attempting to get auth tag in unsupported state')68}69}70StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {71if (this._decrypt) {72this._authTag = tag73} else {74throw new Error('Attempting to set auth tag in unsupported state')75}76}77StreamCipher.prototype.setAAD = function setAAD (buf) {78if (!this._called) {79this._ghash.update(buf)80this._alen += buf.length81} else {82throw new Error('Attempting to set AAD in unsupported state')83}84}85function xorTest (a, b) {86var out = 087if (a.length !== b.length) {88out++89}90var len = Math.min(a.length, b.length)91var i = -192while (++i < len) {93out += (a[i] ^ b[i])94}95return out96}979899