赞
踩
/* eslint-disable no-bitwise, no-mixed-operators, complexity */ const DECRYPT = 0 const ROUND = 32 const BLOCK = 16 const Sbox = [ 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05, 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62, 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6, 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8, 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84, 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48 ] const CK = [ 0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269, 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9, 0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249, 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9, 0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229, 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299, 0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209, 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279 ] /** * 16 进制串转字节数组 */ function hexToArray(str) { const arr = [] for (let i = 0, len = str.length; i < len; i += 2) { arr.push(parseInt(str.substr(i, 2), 16)) } return arr } /** * 字节数组转 16 进制串 */ function ArrayToHex(arr) { return arr.map(item => { item = item.toString(16) return item.length === 1 ? '0' + item : item }).join('') } /** * utf8 串转字节数组 */ function utf8ToArray(str) { const arr = [] for (let i = 0, len = str.length; i < len; i++) { const point = str.codePointAt(i) if (point <= 0x007f) { // 单字节,标量值:00000000 00000000 0zzzzzzz arr.push(point) } else if (point <= 0x07ff) { // 双字节,标量值:00000000 00000yyy yyzzzzzz arr.push(0xc0 | (point >>> 6)) // 110yyyyy(0xc0-0xdf) arr.push(0x80 | (point & 0x3f)) // 10zzzzzz(0x80-0xbf) } else if (point <= 0xD7FF || (point >= 0xE000 && point <= 0xFFFF)) { // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz arr.push(0xe0 | (point >>> 12)) // 1110xxxx(0xe0-0xef) arr.push(0x80 | ((point >>> 6) & 0x3f)) // 10yyyyyy(0x80-0xbf) arr.push(0x80 | (point & 0x3f)) // 10zzzzzz(0x80-0xbf) } else if (point >= 0x010000 && point <= 0x10FFFF) { // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz i++ arr.push((0xf0 | (point >>> 18) & 0x1c)) // 11110www(0xf0-0xf7) arr.push((0x80 | ((point >>> 12) & 0x3f))) // 10xxxxxx(0x80-0xbf) arr.push((0x80 | ((point >>> 6) & 0x3f))) // 10yyyyyy(0x80-0xbf) arr.push((0x80 | (point & 0x3f))) // 10zzzzzz(0x80-0xbf) } else { // 五、六字节,暂时不支持 arr.push(point) throw new Error('input is not supported') } } return arr } /** * 字节数组转 utf8 串 */ function arrayToUtf8(arr) { const str = [] for (let i = 0, len = arr.length; i < len; i++) { if (arr[i] >= 0xf0 && arr[i] <= 0xf7) { // 四字节 str.push(String.fromCodePoint(((arr[i] & 0x07) << 18) + ((arr[i + 1] & 0x3f) << 12) + ((arr[i + 2] & 0x3f) << 6) + (arr[i + 3] & 0x3f))) i += 3 } else if (arr[i] >= 0xe0 && arr[i] <= 0xef) { // 三字节 str.push(String.fromCodePoint(((arr[i] & 0x0f) << 12) + ((arr[i + 1] & 0x3f) << 6) + (arr[i + 2] & 0x3f))) i += 2 } else if (arr[i] >= 0xc0 && arr[i] <= 0xdf) { // 双字节 str.push(String.fromCodePoint(((arr[i] & 0x1f) << 6) + (arr[i + 1] & 0x3f))) i++ } else { // 单字节 str.push(String.fromCodePoint(arr[i])) } } return str.join('') } /** * 32 比特循环左移 */ function rotl(x, y) { return x << y | x >>> (32 - y) } /** * 非线性变换 */ function byteSub(a) { return (Sbox[a >>> 24 & 0xFF] & 0xFF) << 24 | (Sbox[a >>> 16 & 0xFF] & 0xFF) << 16 | (Sbox[a >>> 8 & 0xFF] & 0xFF) << 8 | (Sbox[a & 0xFF] & 0xFF) } /** * 线性变换,加密/解密用 */ function l1(b) { return b ^ rotl(b, 2) ^ rotl(b, 10) ^ rotl(b, 18) ^ rotl(b, 24) } /** * 线性变换,生成轮密钥用 */ function l2(b) { return b ^ rotl(b, 13) ^ rotl(b, 23) } /** * 以一组 128 比特进行加密/解密操作 */ function sms4Crypt(input, output, roundKey) { const x = new Array(4) // 字节数组转成字数组(此处 1 字 = 32 比特) const tmp = new Array(4) for (let i = 0; i < 4; i++) { tmp[0] = input[4 * i] & 0xff tmp[1] = input[4 * i + 1] & 0xff tmp[2] = input[4 * i + 2] & 0xff tmp[3] = input[4 * i + 3] & 0xff x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3] } // x[i + 4] = x[i] ^ l1(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ roundKey[i])) for (let r = 0, mid; r < 32; r += 4) { mid = x[1] ^ x[2] ^ x[3] ^ roundKey[r + 0] x[0] ^= l1(byteSub(mid)) // x[4] mid = x[2] ^ x[3] ^ x[0] ^ roundKey[r + 1] x[1] ^= l1(byteSub(mid)) // x[5] mid = x[3] ^ x[0] ^ x[1] ^ roundKey[r + 2] x[2] ^= l1(byteSub(mid)) // x[6] mid = x[0] ^ x[1] ^ x[2] ^ roundKey[r + 3] x[3] ^= l1(byteSub(mid)) // x[7] } // 反序变换 for (let j = 0; j < 16; j += 4) { output[j] = x[3 - j / 4] >>> 24 & 0xff output[j + 1] = x[3 - j / 4] >>> 16 & 0xff output[j + 2] = x[3 - j / 4] >>> 8 & 0xff output[j + 3] = x[3 - j / 4] & 0xff } } /** * 密钥扩展算法 */ function sms4KeyExt(key, roundKey, cryptFlag) { const x = new Array(4) // 字节数组转成字数组(此处 1 字 = 32 比特) const tmp = new Array(4) for (let i = 0; i < 4; i++) { tmp[0] = key[0 + 4 * i] & 0xff tmp[1] = key[1 + 4 * i] & 0xff tmp[2] = key[2 + 4 * i] & 0xff tmp[3] = key[3 + 4 * i] & 0xff x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3] } // 与系统参数做异或 x[0] ^= 0xa3b1bac6 x[1] ^= 0x56aa3350 x[2] ^= 0x677d9197 x[3] ^= 0xb27022dc // roundKey[i] = x[i + 4] = x[i] ^ l2(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ CK[i])) for (let r = 0, mid; r < 32; r += 4) { mid = x[1] ^ x[2] ^ x[3] ^ CK[r + 0] roundKey[r + 0] = x[0] ^= l2(byteSub(mid)) // x[4] mid = x[2] ^ x[3] ^ x[0] ^ CK[r + 1] roundKey[r + 1] = x[1] ^= l2(byteSub(mid)) // x[5] mid = x[3] ^ x[0] ^ x[1] ^ CK[r + 2] roundKey[r + 2] = x[2] ^= l2(byteSub(mid)) // x[6] mid = x[0] ^ x[1] ^ x[2] ^ CK[r + 3] roundKey[r + 3] = x[3] ^= l2(byteSub(mid)) // x[7] } // 解密时使用反序的轮密钥 if (cryptFlag === DECRYPT) { for (let r = 0, mid; r < 16; r++) { mid = roundKey[r] roundKey[r] = roundKey[31 - r] roundKey[31 - r] = mid } } } function sm4(inArray, key, cryptFlag, { padding = 'pkcs#7', mode, iv = [], output = 'string' } = {}) { if (mode === 'cbc') { // CBC 模式,默认走 ECB 模式 if (typeof iv === 'string') iv = hexToArray(iv) if (iv.length !== (128 / 8)) { // iv 不是 128 比特 throw new Error('iv is invalid') } } // 检查 key if (typeof key === 'string') key = hexToArray(key) if (key.length !== (128 / 8)) { // key 不是 128 比特 throw new Error('key is invalid') } // 检查输入 if (typeof inArray === 'string') { if (cryptFlag !== DECRYPT) { // 加密,输入为 utf8 串 inArray = utf8ToArray(inArray) } else { // 解密,输入为 16 进制串 inArray = hexToArray(inArray) } } else { inArray = [...inArray] } // 新增填充,sm4 是 16 个字节一个分组,所以统一走到 pkcs#7 if ((padding === 'pkcs#5' || padding === 'pkcs#7') && cryptFlag !== DECRYPT) { const paddingCount = BLOCK - inArray.length % BLOCK for (let i = 0; i < paddingCount; i++) inArray.push(paddingCount) } // 生成轮密钥 const roundKey = new Array(ROUND) sms4KeyExt(key, roundKey, cryptFlag) const outArray = [] let lastVector = iv let restLen = inArray.length let point = 0 while (restLen >= BLOCK) { const input = inArray.slice(point, point + 16) const output = new Array(16) if (mode === 'cbc') { for (let i = 0; i < BLOCK; i++) { if (cryptFlag !== DECRYPT) { // 加密过程在组加密前进行异或 input[i] ^= lastVector[i] } } } sms4Crypt(input, output, roundKey) for (let i = 0; i < BLOCK; i++) { if (mode === 'cbc') { if (cryptFlag === DECRYPT) { // 解密过程在组解密后进行异或 output[i] ^= lastVector[i] } } outArray[point + i] = output[i] } if (mode === 'cbc') { if (cryptFlag !== DECRYPT) { // 使用上一次输出作为加密向量 lastVector = output } else { // 使用上一次输入作为解密向量 lastVector = input } } restLen -= BLOCK point += BLOCK } // 去除填充,sm4 是 16 个字节一个分组,所以统一走到 pkcs#7 if ((padding === 'pkcs#5' || padding === 'pkcs#7') && cryptFlag === DECRYPT) { const paddingCount = outArray[outArray.length - 1] outArray.splice(outArray.length - paddingCount, paddingCount) } // 调整输出 if (output !== 'array') { if (cryptFlag !== DECRYPT) { // 加密,输出转 16 进制串 return ArrayToHex(outArray) } else { // 解密,输出转 utf8 串 return arrayToUtf8(outArray) } } else { return outArray } } module.exports = { encrypt(inArray, key, options) { return sm4(inArray, key, 1, options) }, decrypt(inArray, key, options) { return sm4(inArray, key, 0, options) } }
const sm4 = require('../sm4') const forge = require('./forge'); require('./util'); function arrayCopy(src, pos1, dest, pos2, len) { var realLen = len; if (pos1 + len > src.length && pos2 + len <= dest.length) { realLen = src.length - pos1; } else if (pos2 + len > dest.length && pos1 + len <= src.length) { realLen = dest.length - pos2; } else if (pos1 + len <= src.length && pos2 + len <= dest.length) { realLen = len; } else if (dest.length < src.length) { realLen = dest.length - pos2; } else { realLen = src.length - pos2; } for (var i = 0; i < realLen; i++) { dest[i + pos2] = src[i + pos1]; } } function intArrayToByteArray(nums) { var b = new Array(nums.length * 4); for (var i = 0; i < nums.length; i++) { arrayCopy(intToByte(nums[i]), 0, b, i * 4, 4); } return b; } function byteArrayToIntArray(b) { var arrLen = Math.ceil(b.length / 4); var out = new Array(arrLen); for (var i = 0; i < b.length; i++) { b[i] = b[i] & 0xFF; } for (var i = 0; i < out.length; i++) { out[i] = byteToInt(b, i * 4); } return out; } function byteToInt(b, pos) { if (pos + 3 < b.length) { return ((b[pos]) << 24) | ((b[pos + 1]) << 16) | ((b[pos + 2]) << 8) | ((b[pos + 3])); } else if (pos + 2 < b.length) { return ((b[pos + 1]) << 16) | ((b[pos + 2]) << 8) | ((b[pos + 3])); } else if (pos + 1 < b.length) { return ((b[pos]) << 8) | ((b[pos + 1])); } else { return ((b[pos])); } } function sm4ecb(key, inArray) { var inByteArray = intArrayToByteArray(inArray); var outByteArray = sm4.encrypt(inByteArray, key, {padding: 'none', mode: 'ecb', output: 'array'}); var outArray = byteArrayToIntArray(outByteArray); return outArray; } var gcm = module.exports = function gcm(options) { options = options || {}; this.name = 'GCM'; this.blockSize = 16; this.key = options.key; this._ints = this.blockSize / 4; this._inBlock = new Array(this._ints); this._outBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; // R is actually this value concatenated with 120 more zero bits, but // we only XOR against R so the other zeros have no effect -- we just // apply this value to the first integer in a block this._R = 0xE1000000; }; gcm.prototype.start = function (options) { if (!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // ensure IV is a byte buffer var iv = forge.util.createBuffer(options.iv); // no ciphered data processed yet this._cipherLength = 0; // default additional data is none var additionalData; if ('additionalData' in options) { additionalData = forge.util.createBuffer(options.additionalData); } else { additionalData = forge.util.createBuffer(); } // default tag length is 128 bits if ('tagLength' in options) { this._tagLength = options.tagLength; } else { this._tagLength = 128; } // if tag is given, ensure tag matches tag length this._tag = null; if (options.decrypt) { // save tag to check later this._tag = forge.util.createBuffer(options.tag).getBytes(); if (this._tag.length !== (this._tagLength / 8)) { throw new Error('Authentication tag does not match tag length.'); } } // create tmp storage for hash calculation this._hashBlock = new Array(this._ints); // no tag generated yet this.tag = null; // generate hash subkey // (apply block cipher to "zero" block) this._hashSubkey = new Array(this._ints); //this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); this._hashSubkey = sm4ecb(this.key, [0, 0, 0, 0]); // generate table M // use 4-bit tables (32 component decomposition of a 16 byte value) // 8-bit tables take more space and are known to have security // vulnerabilities (in native implementations) this.componentBits = 4; this._m = this.generateHashTable(this._hashSubkey, this.componentBits); // Note: support IV length different from 96 bits? (only supporting // 96 bits is recommended by NIST SP-800-38D) // generate J_0 var ivLength = iv.length(); if (ivLength === 12) { // 96-bit IV this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; } else { // IV is NOT 96-bits this._j0 = [0, 0, 0, 0]; while (iv.length() > 0) { this._j0 = this.ghash( this._hashSubkey, this._j0, [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); } this._j0 = this.ghash( this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); } // generate ICB (initial counter block) this._inBlock = this._j0.slice(0); inc32(this._inBlock); this._partialBytes = 0; // consume authentication data additionalData = forge.util.createBuffer(additionalData); // save additional data length as a BE 64-bit number this._aDataLength = from64To32(additionalData.length() * 8); // pad additional data to 128 bit (16 byte) block size var overflow = additionalData.length() % this.blockSize; if (overflow) { additionalData.fillWithByte(0, this.blockSize - overflow); } this._s = [0, 0, 0, 0]; while (additionalData.length() > 0) { this._s = this.ghash(this._hashSubkey, this._s, [ additionalData.getInt32(), additionalData.getInt32(), additionalData.getInt32(), additionalData.getInt32() ]); } }; gcm.prototype.encrypt = function (input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if (inputLength === 0) { return true; } // encrypt block //this.cipher.encrypt(this._inBlock, this._outBlock); this._outBlock = sm4ecb(this.key, this._inBlock); // handle full block if (this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output for (var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i] ^= input.getInt32()); } this._cipherLength += this.blockSize; } else { // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if (partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output this._partialOutput.clear(); for (var i = 0; i < this._ints; ++i) { this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } if (partialBytes <= 0 || finish) { // handle overflow prior to hashing if (finish) { // get block overflow var overflow = inputLength % this.blockSize; this._cipherLength += overflow; // truncate for hash function this._partialOutput.truncate(this.blockSize - overflow); } else { this._cipherLength += this.blockSize; } // get output block for hashing for (var i = 0; i < this._ints; ++i) { this._outBlock[i] = this._partialOutput.getInt32(); } this._partialOutput.read -= this.blockSize; } // skip any previous partial bytes if (this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if (partialBytes > 0 && !finish) { // block still incomplete, restore input buffer, get partial output, // and return early input.read -= this.blockSize; output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; } // update hash block S this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); // increment counter (input block) inc32(this._inBlock); }; gcm.prototype.decrypt = function (input, output, finish) { // not enough input to decrypt var inputLength = input.length(); if (inputLength < this.blockSize && !(finish && inputLength > 0)) { return true; } // encrypt block (GCM always uses encryption mode) //this.cipher.encrypt(this._inBlock, this._outBlock); this._outBlock = sm4ecb(this.key, this._inBlock); // increment counter (input block) inc32(this._inBlock); // update hash block S this._hashBlock[0] = input.getInt32(); this._hashBlock[1] = input.getInt32(); this._hashBlock[2] = input.getInt32(); this._hashBlock[3] = input.getInt32(); this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); // XOR hash input with output for (var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); } // increment cipher data length if (inputLength < this.blockSize) { this._cipherLength += inputLength % this.blockSize; } else { this._cipherLength += this.blockSize; } }; gcm.prototype.afterFinish = function (output, options) { var rval = true; // handle overflow if (options.decrypt && options.overflow) { output.truncate(this.blockSize - options.overflow); } // handle authentication tag this.tag = forge.util.createBuffer(); // concatenate additional data length with cipher length var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); // include lengths in hash this._s = this.ghash(this._hashSubkey, this._s, lengths); // do GCTR(J_0, S) var tag = []; //this.cipher.encrypt(this._j0, tag); tag = sm4ecb(this.key, this._j0); for (var i = 0; i < this._ints; ++i) { this.tag.putInt32(this._s[i] ^ tag[i]); } // trim tag to length this.tag.truncate(this.tag.length() % (this._tagLength / 8)); // check authentication tag if (options.decrypt && this.tag.bytes() !== this._tag) { rval = false; } return rval; }; /** * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois * field multiplication. The field, GF(2^128), is defined by the polynomial: * * x^128 + x^7 + x^2 + x + 1 * * Which is represented in little-endian binary form as: 11100001 (0xe1). When * the value of a coefficient is 1, a bit is set. The value R, is the * concatenation of this value and 120 zero bits, yielding a 128-bit value * which matches the block size. * * This function will multiply two elements (vectors of bytes), X and Y, in * the field GF(2^128). The result is initialized to zero. For each bit of * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) * by the current value of Y. For each bit, the value of Y will be raised by * a power of x (multiplied by the polynomial x). This can be achieved by * shifting Y once to the right. If the current value of Y, prior to being * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. * Otherwise, we must divide by R after shifting to find the remainder. * * @param x the first block to multiply by the second. * @param y the second block to multiply by the first. * * @return the block result of the multiplication. */ gcm.prototype.multiply = function (x, y) { var z_i = [0, 0, 0, 0]; var v_i = y.slice(0); // calculate Z_128 (block has 128 bits) for (var i = 0; i < 128; ++i) { // if x_i is 0, Z_{i+1} = Z_i (unchanged) // else Z_{i+1} = Z_i ^ V_i // get x_i by finding 32-bit int position, then left shift 1 by remainder var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); if (x_i) { z_i[0] ^= v_i[0]; z_i[1] ^= v_i[1]; z_i[2] ^= v_i[2]; z_i[3] ^= v_i[3]; } // if LSB(V_i) is 1, V_i = V_i >> 1 // else V_i = (V_i >> 1) ^ R this.pow(v_i, v_i); } return z_i; }; gcm.prototype.pow = function (x, out) { // if LSB(x) is 1, x = x >>> 1 // else x = (x >>> 1) ^ R var lsb = x[3] & 1; // always do x >>> 1: // starting with the rightmost integer, shift each integer to the right // one bit, pulling in the bit from the integer to the left as its top // most bit (do this for the last 3 integers) for (var i = 3; i > 0; --i) { out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); } // shift the first integer normally out[0] = x[0] >>> 1; // if lsb was not set, then polynomial had a degree of 127 and doesn't // need to divided; otherwise, XOR with R to find the remainder; we only // need to XOR the first integer since R technically ends w/120 zero bits if (lsb) { out[0] ^= this._R; } }; gcm.prototype.tableMultiply = function (x) { // assumes 4-bit tables are used var z = [0, 0, 0, 0]; for (var i = 0; i < 32; ++i) { var idx = (i / 8) | 0; var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; var ah = this._m[i][x_i]; z[0] ^= ah[0]; z[1] ^= ah[1]; z[2] ^= ah[2]; z[3] ^= ah[3]; } return z; }; /** * A continuing version of the GHASH algorithm that operates on a single * block. The hash block, last hash value (Ym) and the new block to hash * are given. * * @param h the hash block. * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. * @param x the block to hash. * * @return the hashed value (Ym). */ gcm.prototype.ghash = function (h, y, x) { y[0] ^= x[0]; y[1] ^= x[1]; y[2] ^= x[2]; y[3] ^= x[3]; return this.tableMultiply(y); //return this.multiply(y, h); }; /** * Precomputes a table for multiplying against the hash subkey. This * mechanism provides a substantial speed increase over multiplication * performed without a table. The table-based multiplication this table is * for solves X * H by multiplying each component of X by H and then * composing the results together using XOR. * * This function can be used to generate tables with different bit sizes * for the components, however, this implementation assumes there are * 32 components of X (which is a 16 byte vector), therefore each component * takes 4-bits (so the table is constructed with bits=4). * * @param h the hash subkey. * @param bits the bit size for a component. */ gcm.prototype.generateHashTable = function (h, bits) { // TODO: There are further optimizations that would use only the // first table M_0 (or some variant) along with a remainder table; // this can be explored in the future var multiplier = 8 / bits; var perInt = 4 * multiplier; var size = 16 * multiplier; var m = new Array(size); for (var i = 0; i < size; ++i) { var tmp = [0, 0, 0, 0]; var idx = (i / perInt) | 0; var shft = ((perInt - 1 - (i % perInt)) * bits); tmp[idx] = (1 << (bits - 1)) << shft; m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); } return m; }; /** * Generates a table for multiplying against the hash subkey for one * particular component (out of all possible component values). * * @param mid the pre-multiplied value for the middle key of the table. * @param bits the bit size for a component. */ gcm.prototype.generateSubHashTable = function (mid, bits) { // compute the table quickly by minimizing the number of // POW operations -- they only need to be performed for powers of 2, // all other entries can be composed from those powers using XOR var size = 1 << bits; var half = size >>> 1; var m = new Array(size); m[half] = mid.slice(0); var i = half >>> 1; while (i > 0) { // raise m0[2 * i] and store in m0[i] this.pow(m[2 * i], m[i] = []); i >>= 1; } i = 2; while (i < half) { for (var j = 1; j < i; ++j) { var m_i = m[i]; var m_j = m[j]; m[i + j] = [ m_i[0] ^ m_j[0], m_i[1] ^ m_j[1], m_i[2] ^ m_j[2], m_i[3] ^ m_j[3] ]; } i *= 2; } m[0] = [0, 0, 0, 0]; /* Note: We could avoid storing these by doing composition during multiply calculate top half using composition by speed is preferred. */ for (i = half + 1; i < size; ++i) { var c = m[i ^ half]; m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; } return m; }; /** Utility functions */ function transformIV(iv, blockSize) { if (typeof iv === 'string') { // convert iv string into byte buffer iv = forge.util.createBuffer(iv); } if (forge.util.isArray(iv) && iv.length > 4) { // convert iv byte array into byte buffer var tmp = iv; iv = forge.util.createBuffer(); for (var i = 0; i < tmp.length; ++i) { iv.putByte(tmp[i]); } } if (iv.length() < blockSize) { throw new Error( 'Invalid IV length; got ' + iv.length() + ' bytes and expected ' + blockSize + ' bytes.'); } if (!forge.util.isArray(iv)) { // convert iv byte buffer into 32-bit integer array var ints = []; var blocks = blockSize / 4; for (var i = 0; i < blocks; ++i) { ints.push(iv.getInt32()); } iv = ints; } return iv; } function inc32(block) { // increment last 32 bits of block only block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; } function from64To32(num) { // convert 64-bit number to two BE Int32s return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; } function intToByte(num) { return new Array( (num >> 24) & 0x000000FF, (num >> 16) & 0x000000FF, (num >> 8) & 0x000000FF, (num) & 0x000000FF ); }
baseN.js
/** * Base-N/Base-X encoding/decoding functions. * * Original implementation from base-x: * https://github.com/cryptocoinjs/base-x * * Which is MIT licensed: * * The MIT License (MIT) * * Copyright base-x contributors (c) 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ var api = {}; module.exports = api; // baseN alphabet indexes var _reverseAlphabets = {}; /** * BaseN-encodes a Uint8Array using the given alphabet. * * @param input the Uint8Array to encode. * @param maxline the maximum number of encoded characters per line to use, * defaults to none. * * @return the baseN-encoded output string. */ api.encode = function(input, alphabet, maxline) { if(typeof alphabet !== 'string') { throw new TypeError('"alphabet" must be a string.'); } if(maxline !== undefined && typeof maxline !== 'number') { throw new TypeError('"maxline" must be a number.'); } var output = ''; if(!(input instanceof Uint8Array)) { // assume forge byte buffer output = _encodeWithByteBuffer(input, alphabet); } else { var i = 0; var base = alphabet.length; var first = alphabet.charAt(0); var digits = [0]; for(i = 0; i < input.length; ++i) { for(var j = 0, carry = input[i]; j < digits.length; ++j) { carry += digits[j] << 8; digits[j] = carry % base; carry = (carry / base) | 0; } while(carry > 0) { digits.push(carry % base); carry = (carry / base) | 0; } } // deal with leading zeros for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { output += first; } // convert digits to a string for(i = digits.length - 1; i >= 0; --i) { output += alphabet[digits[i]]; } } if(maxline) { var regex = new RegExp('.{1,' + maxline + '}', 'g'); output = output.match(regex).join('\r\n'); } return output; }; /** * Decodes a baseN-encoded (using the given alphabet) string to a * Uint8Array. * * @param input the baseN-encoded input string. * * @return the Uint8Array. */ api.decode = function(input, alphabet) { if(typeof input !== 'string') { throw new TypeError('"input" must be a string.'); } if(typeof alphabet !== 'string') { throw new TypeError('"alphabet" must be a string.'); } var table = _reverseAlphabets[alphabet]; if(!table) { // compute reverse alphabet table = _reverseAlphabets[alphabet] = []; for(var i = 0; i < alphabet.length; ++i) { table[alphabet.charCodeAt(i)] = i; } } // remove whitespace characters input = input.replace(/\s/g, ''); var base = alphabet.length; var first = alphabet.charAt(0); var bytes = [0]; for(var i = 0; i < input.length; i++) { var value = table[input.charCodeAt(i)]; if(value === undefined) { return; } for(var j = 0, carry = value; j < bytes.length; ++j) { carry += bytes[j] * base; bytes[j] = carry & 0xff; carry >>= 8; } while(carry > 0) { bytes.push(carry & 0xff); carry >>= 8; } } // deal with leading zeros for(var k = 0; input[k] === first && k < input.length - 1; ++k) { bytes.push(0); } if(typeof Buffer !== 'undefined') { return Buffer.from(bytes.reverse()); } return new Uint8Array(bytes.reverse()); }; function _encodeWithByteBuffer(input, alphabet) { var i = 0; var base = alphabet.length; var first = alphabet.charAt(0); var digits = [0]; for(i = 0; i < input.length(); ++i) { for(var j = 0, carry = input.at(i); j < digits.length; ++j) { carry += digits[j] << 8; digits[j] = carry % base; carry = (carry / base) | 0; } while(carry > 0) { digits.push(carry % base); carry = (carry / base) | 0; } } var output = ''; // deal with leading zeros for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { output += first; } // convert digits to a string for(i = digits.length - 1; i >= 0; --i) { output += alphabet[digits[i]]; } return output; }
forge.js
/**
* Node.js module for Forge.
*
* @author Dave Longley
*
* Copyright 2011-2016 Digital Bazaar, Inc.
*/
module.exports = {
// default options
options: {
usePureJavaScript: false
}
};
util.js
/** * Node.js module for Forge. * * @author Dave Longley * * Copyright 2011-2016 Digital Bazaar, Inc. */ /** * Utility functions for web applications. * * @author Dave Longley * * Copyright (c) 2010-2018 Digital Bazaar, Inc. */ var forge = require('./forge'); var baseN = require('./baseN'); /* Utilities API */ var util = module.exports = forge.util = forge.util || {}; // define setImmediate and nextTick (function() { // use native nextTick (unless we're in webpack) // webpack (or better node-libs-browser polyfill) sets process.browser. // this way we can detect webpack properly if(typeof process !== 'undefined' && process.nextTick && !process.browser) { util.nextTick = process.nextTick; if(typeof setImmediate === 'function') { util.setImmediate = setImmediate; } else { // polyfill setImmediate with nextTick, older versions of node // (those w/o setImmediate) won't totally starve IO util.setImmediate = util.nextTick; } return; } // polyfill nextTick with native setImmediate if(typeof setImmediate === 'function') { util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; util.nextTick = function(callback) { return setImmediate(callback); }; return; } /* Note: A polyfill upgrade pattern is used here to allow combining polyfills. For example, MutationObserver is fast, but blocks UI updates, so it needs to allow UI updates periodically, so it falls back on postMessage or setTimeout. */ // polyfill with setTimeout util.setImmediate = function(callback) { setTimeout(callback, 0); }; // upgrade polyfill to use postMessage if(typeof window !== 'undefined' && typeof window.postMessage === 'function') { var msg = 'forge.setImmediate'; var callbacks = []; util.setImmediate = function(callback) { callbacks.push(callback); // only send message when one hasn't been sent in // the current turn of the event loop if(callbacks.length === 1) { window.postMessage(msg, '*'); } }; function handler(event) { if(event.source === window && event.data === msg) { event.stopPropagation(); var copy = callbacks.slice(); callbacks.length = 0; copy.forEach(function(callback) { callback(); }); } } window.addEventListener('message', handler, true); } // upgrade polyfill to use MutationObserver if(typeof MutationObserver !== 'undefined') { // polyfill with MutationObserver var now = Date.now(); var attr = true; var div = document.createElement('div'); var callbacks = []; new MutationObserver(function() { var copy = callbacks.slice(); callbacks.length = 0; copy.forEach(function(callback) { callback(); }); }).observe(div, {attributes: true}); var oldSetImmediate = util.setImmediate; util.setImmediate = function(callback) { if(Date.now() - now > 15) { now = Date.now(); oldSetImmediate(callback); } else { callbacks.push(callback); // only trigger observer when it hasn't been triggered in // the current turn of the event loop if(callbacks.length === 1) { div.setAttribute('a', attr = !attr); } } }; } util.nextTick = util.setImmediate; })(); // check if running under Node.js util.isNodejs = typeof process !== 'undefined' && process.versions && process.versions.node; // 'self' will also work in Web Workers (instance of WorkerGlobalScope) while // it will point to `window` in the main thread. // To remain compatible with older browsers, we fall back to 'window' if 'self' // is not available. util.globalScope = (function() { if(util.isNodejs) { return global; } return typeof self === 'undefined' ? window : self; })(); // define isArray util.isArray = Array.isArray || function(x) { return Object.prototype.toString.call(x) === '[object Array]'; }; // define isArrayBuffer util.isArrayBuffer = function(x) { return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; }; // define isArrayBufferView util.isArrayBufferView = function(x) { return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; }; /** * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for * algorithms where bit manipulation, JavaScript limitations, and/or algorithm * design only allow for byte operations of a limited size. * * @param n number of bits. * * Throw Error if n invalid. */ function _checkBitsParam(n) { if(!(n === 8 || n === 16 || n === 24 || n === 32)) { throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); } } // TODO: set ByteBuffer to best available backing util.ByteBuffer = ByteStringBuffer; /** Buffer w/BinaryString backing */ /** * Constructor for a binary string backed byte buffer. * * @param [b] the bytes to wrap (either encoded as string, one byte per * character, or as an ArrayBuffer or Typed Array). */ function ByteStringBuffer(b) { // TODO: update to match DataBuffer API // the data in this buffer this.data = ''; // the pointer for reading from this buffer this.read = 0; if(typeof b === 'string') { this.data = b; } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { if(typeof Buffer !== 'undefined' && b instanceof Buffer) { this.data = b.toString('binary'); } else { // convert native buffer to forge buffer // FIXME: support native buffers internally instead var arr = new Uint8Array(b); try { this.data = String.fromCharCode.apply(null, arr); } catch(e) { for(var i = 0; i < arr.length; ++i) { this.putByte(arr[i]); } } } } else if(b instanceof ByteStringBuffer || (typeof b === 'object' && typeof b.data === 'string' && typeof b.read === 'number')) { // copy existing buffer this.data = b.data; this.read = b.read; } // used for v8 optimization this._constructedStringLength = 0; } util.ByteStringBuffer = ByteStringBuffer; /* Note: This is an optimization for V8-based browsers. When V8 concatenates a string, the strings are only joined logically using a "cons string" or "constructed/concatenated string". These containers keep references to one another and can result in very large memory usage. For example, if a 2MB string is constructed by concatenating 4 bytes together at a time, the memory usage will be ~44MB; so ~22x increase. The strings are only joined together when an operation requiring their joining takes place, such as substr(). This function is called when adding data to this buffer to ensure these types of strings are periodically joined to reduce the memory footprint. */ var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { this._constructedStringLength += x; if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { // this substr() should cause the constructed string to join this.data.substr(0, 1); this._constructedStringLength = 0; } }; /** * Gets the number of bytes in this buffer. * * @return the number of bytes in this buffer. */ util.ByteStringBuffer.prototype.length = function() { return this.data.length - this.read; }; /** * Gets whether or not this buffer is empty. * * @return true if this buffer is empty, false if not. */ util.ByteStringBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; /** * Puts a byte in this buffer. * * @param b the byte to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putByte = function(b) { return this.putBytes(String.fromCharCode(b)); }; /** * Puts a byte in this buffer N times. * * @param b the byte to put. * @param n the number of bytes of value b to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { b = String.fromCharCode(b); var d = this.data; while(n > 0) { if(n & 1) { d += b; } n >>>= 1; if(n > 0) { b += b; } } this.data = d; this._optimizeConstructedString(n); return this; }; /** * Puts bytes in this buffer. * * @param bytes the bytes (as a binary encoded string) to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putBytes = function(bytes) { this.data += bytes; this._optimizeConstructedString(bytes.length); return this; }; /** * Puts a UTF-16 encoded string into this buffer. * * @param str the string to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putString = function(str) { return this.putBytes(util.encodeUtf8(str)); }; /** * Puts a 16-bit integer in this buffer in big-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt16 = function(i) { return this.putBytes( String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 24-bit integer in this buffer in big-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt24 = function(i) { return this.putBytes( String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 32-bit integer in this buffer in big-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt32 = function(i) { return this.putBytes( String.fromCharCode(i >> 24 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 16-bit integer in this buffer in little-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt16Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF)); }; /** * Puts a 24-bit integer in this buffer in little-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt24Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF)); }; /** * Puts a 32-bit integer in this buffer in little-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt32Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 24 & 0xFF)); }; /** * Puts an n-bit integer in this buffer in big-endian order. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); var bytes = ''; do { n -= 8; bytes += String.fromCharCode((i >> n) & 0xFF); } while(n > 0); return this.putBytes(bytes); }; /** * Puts a signed n-bit integer in this buffer in big-endian order. Two's * complement representation is used. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { // putInt checks n if(i < 0) { i += 2 << (n - 1); } return this.putInt(i, n); }; /** * Puts the given buffer into this buffer. * * @param buffer the buffer to put into this one. * * @return this buffer. */ util.ByteStringBuffer.prototype.putBuffer = function(buffer) { return this.putBytes(buffer.getBytes()); }; /** * Gets a byte from this buffer and advances the read pointer by 1. * * @return the byte. */ util.ByteStringBuffer.prototype.getByte = function() { return this.data.charCodeAt(this.read++); }; /** * Gets a uint16 from this buffer in big-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.ByteStringBuffer.prototype.getInt16 = function() { var rval = ( this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1)); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in big-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.ByteStringBuffer.prototype.getInt24 = function() { var rval = ( this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2)); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in big-endian order and advances the read * pointer by 4. * * @return the word. */ util.ByteStringBuffer.prototype.getInt32 = function() { var rval = ( this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3)); this.read += 4; return rval; }; /** * Gets a uint16 from this buffer in little-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.ByteStringBuffer.prototype.getInt16Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in little-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.ByteStringBuffer.prototype.getInt24Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in little-endian order and advances the read * pointer by 4. * * @return the word. */ util.ByteStringBuffer.prototype.getInt32Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24); this.read += 4; return rval; }; /** * Gets an n-bit integer from this buffer in big-endian order and advances the * read pointer by ceil(n/8). * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.ByteStringBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. rval = (rval << 8) + this.data.charCodeAt(this.read++); n -= 8; } while(n > 0); return rval; }; /** * Gets a signed n-bit integer from this buffer in big-endian order, using * two's complement, and advances the read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.ByteStringBuffer.prototype.getSignedInt = function(n) { // getInt checks n var x = this.getInt(n); var max = 2 << (n - 2); if(x >= max) { x -= max << 1; } return x; }; /** * Reads bytes out as a binary encoded string and clears them from the * buffer. Note that the resulting string is binary encoded (in node.js this * encoding is referred to as `binary`, it is *not* `utf8`). * * @param count the number of bytes to read, undefined or null for all. * * @return a binary encoded string of bytes. */ util.ByteStringBuffer.prototype.getBytes = function(count) { var rval; if(count) { // read count bytes count = Math.min(this.length(), count); rval = this.data.slice(this.read, this.read + count); this.read += count; } else if(count === 0) { rval = ''; } else { // read all bytes, optimize to only copy when needed rval = (this.read === 0) ? this.data : this.data.slice(this.read); this.clear(); } return rval; }; /** * Gets a binary encoded string of the bytes from this buffer without * modifying the read pointer. * * @param count the number of bytes to get, omit to get all. * * @return a string full of binary encoded characters. */ util.ByteStringBuffer.prototype.bytes = function(count) { return (typeof(count) === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count)); }; /** * Gets a byte at the given index without modifying the read pointer. * * @param i the byte index. * * @return the byte. */ util.ByteStringBuffer.prototype.at = function(i) { return this.data.charCodeAt(this.read + i); }; /** * Puts a byte at the given index without modifying the read pointer. * * @param i the byte index. * @param b the byte to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.setAt = function(i, b) { this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); return this; }; /** * Gets the last byte without modifying the read pointer. * * @return the last byte. */ util.ByteStringBuffer.prototype.last = function() { return this.data.charCodeAt(this.data.length - 1); }; /** * Creates a copy of this buffer. * * @return the copy. */ util.ByteStringBuffer.prototype.copy = function() { var c = util.createBuffer(this.data); c.read = this.read; return c; }; /** * Compacts this buffer. * * @return this buffer. */ util.ByteStringBuffer.prototype.compact = function() { if(this.read > 0) { this.data = this.data.slice(this.read); this.read = 0; } return this; }; /** * Clears this buffer. * * @return this buffer. */ util.ByteStringBuffer.prototype.clear = function() { this.data = ''; this.read = 0; return this; }; /** * Shortens this buffer by triming bytes off of the end of this buffer. * * @param count the number of bytes to trim off. * * @return this buffer. */ util.ByteStringBuffer.prototype.truncate = function(count) { var len = Math.max(0, this.length() - count); this.data = this.data.substr(this.read, len); this.read = 0; return this; }; /** * Converts this buffer to a hexadecimal string. * * @return a hexadecimal string. */ util.ByteStringBuffer.prototype.toHex = function() { var rval = ''; for(var i = this.read; i < this.data.length; ++i) { var b = this.data.charCodeAt(i); if(b < 16) { rval += '0'; } rval += b.toString(16); } return rval; }; /** * Converts this buffer to a UTF-16 string (standard JavaScript string). * * @return a UTF-16 string. */ util.ByteStringBuffer.prototype.toString = function() { return util.decodeUtf8(this.bytes()); }; /** End Buffer w/BinaryString backing */ /** Buffer w/UInt8Array backing */ /** * FIXME: Experimental. Do not use yet. * * Constructor for an ArrayBuffer-backed byte buffer. * * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a * TypedArray. * * If a string is given, its encoding should be provided as an option, * otherwise it will default to 'binary'. A 'binary' string is encoded such * that each character is one byte in length and size. * * If an ArrayBuffer, DataView, or TypedArray is given, it will be used * *directly* without any copying. Note that, if a write to the buffer requires * more space, the buffer will allocate a new backing ArrayBuffer to * accommodate. The starting read and write offsets for the buffer may be * given as options. * * @param [b] the initial bytes for this buffer. * @param options the options to use: * [readOffset] the starting read offset to use (default: 0). * [writeOffset] the starting write offset to use (default: the * length of the first parameter). * [growSize] the minimum amount, in bytes, to grow the buffer by to * accommodate writes (default: 1024). * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the * first parameter, if it is a string (default: 'binary'). */ function DataBuffer(b, options) { // default options options = options || {}; // pointers for read from/write to buffer this.read = options.readOffset || 0; this.growSize = options.growSize || 1024; var isArrayBuffer = util.isArrayBuffer(b); var isArrayBufferView = util.isArrayBufferView(b); if(isArrayBuffer || isArrayBufferView) { // use ArrayBuffer directly if(isArrayBuffer) { this.data = new DataView(b); } else { // TODO: adjust read/write offset based on the type of view // or specify that this must be done in the options ... that the // offsets are byte-based this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); } this.write = ('writeOffset' in options ? options.writeOffset : this.data.byteLength); return; } // initialize to empty array buffer and add any given bytes using putBytes this.data = new DataView(new ArrayBuffer(0)); this.write = 0; if(b !== null && b !== undefined) { this.putBytes(b); } if('writeOffset' in options) { this.write = options.writeOffset; } } util.DataBuffer = DataBuffer; /** * Gets the number of bytes in this buffer. * * @return the number of bytes in this buffer. */ util.DataBuffer.prototype.length = function() { return this.write - this.read; }; /** * Gets whether or not this buffer is empty. * * @return true if this buffer is empty, false if not. */ util.DataBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; /** * Ensures this buffer has enough empty space to accommodate the given number * of bytes. An optional parameter may be given that indicates a minimum * amount to grow the buffer if necessary. If the parameter is not given, * the buffer will be grown by some previously-specified default amount * or heuristic. * * @param amount the number of bytes to accommodate. * @param [growSize] the minimum amount, in bytes, to grow the buffer by if * necessary. */ util.DataBuffer.prototype.accommodate = function(amount, growSize) { if(this.length() >= amount) { return this; } growSize = Math.max(growSize || this.growSize, amount); // grow buffer var src = new Uint8Array( this.data.buffer, this.data.byteOffset, this.data.byteLength); var dst = new Uint8Array(this.length() + growSize); dst.set(src); this.data = new DataView(dst.buffer); return this; }; /** * Puts a byte in this buffer. * * @param b the byte to put. * * @return this buffer. */ util.DataBuffer.prototype.putByte = function(b) { this.accommodate(1); this.data.setUint8(this.write++, b); return this; }; /** * Puts a byte in this buffer N times. * * @param b the byte to put. * @param n the number of bytes of value b to put. * * @return this buffer. */ util.DataBuffer.prototype.fillWithByte = function(b, n) { this.accommodate(n); for(var i = 0; i < n; ++i) { this.data.setUint8(b); } return this; }; /** * Puts bytes in this buffer. The bytes may be given as a string, an * ArrayBuffer, a DataView, or a TypedArray. * * @param bytes the bytes to put. * @param [encoding] the encoding for the first parameter ('binary', 'utf8', * 'utf16', 'hex'), if it is a string (default: 'binary'). * * @return this buffer. */ util.DataBuffer.prototype.putBytes = function(bytes, encoding) { if(util.isArrayBufferView(bytes)) { var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); var len = src.byteLength - src.byteOffset; this.accommodate(len); var dst = new Uint8Array(this.data.buffer, this.write); dst.set(src); this.write += len; return this; } if(util.isArrayBuffer(bytes)) { var src = new Uint8Array(bytes); this.accommodate(src.byteLength); var dst = new Uint8Array(this.data.buffer); dst.set(src, this.write); this.write += src.byteLength; return this; } // bytes is a util.DataBuffer or equivalent if(bytes instanceof util.DataBuffer || (typeof bytes === 'object' && typeof bytes.read === 'number' && typeof bytes.write === 'number' && util.isArrayBufferView(bytes.data))) { var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); this.accommodate(src.byteLength); var dst = new Uint8Array(bytes.data.byteLength, this.write); dst.set(src); this.write += src.byteLength; return this; } if(bytes instanceof util.ByteStringBuffer) { // copy binary string and process as the same as a string parameter below bytes = bytes.data; encoding = 'binary'; } // string conversion encoding = encoding || 'binary'; if(typeof bytes === 'string') { var view; // decode from string if(encoding === 'hex') { this.accommodate(Math.ceil(bytes.length / 2)); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.hex.decode(bytes, view, this.write); return this; } if(encoding === 'base64') { this.accommodate(Math.ceil(bytes.length / 4) * 3); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.base64.decode(bytes, view, this.write); return this; } // encode text as UTF-8 bytes if(encoding === 'utf8') { // encode as UTF-8 then decode string as raw binary bytes = util.encodeUtf8(bytes); encoding = 'binary'; } // decode string as raw binary if(encoding === 'binary' || encoding === 'raw') { // one byte per character this.accommodate(bytes.length); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.raw.decode(view); return this; } // encode text as UTF-16 bytes if(encoding === 'utf16') { // two bytes per character this.accommodate(bytes.length * 2); view = new Uint16Array(this.data.buffer, this.write); this.write += util.text.utf16.encode(view); return this; } throw new Error('Invalid encoding: ' + encoding); } throw Error('Invalid parameter: ' + bytes); }; /** * Puts the given buffer into this buffer. * * @param buffer the buffer to put into this one. * * @return this buffer. */ util.DataBuffer.prototype.putBuffer = function(buffer) { this.putBytes(buffer); buffer.clear(); return this; }; /** * Puts a string into this buffer. * * @param str the string to put. * @param [encoding] the encoding for the string (default: 'utf16'). * * @return this buffer. */ util.DataBuffer.prototype.putString = function(str) { return this.putBytes(str, 'utf16'); }; /** * Puts a 16-bit integer in this buffer in big-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt16 = function(i) { this.accommodate(2); this.data.setInt16(this.write, i); this.write += 2; return this; }; /** * Puts a 24-bit integer in this buffer in big-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt24 = function(i) { this.accommodate(3); this.data.setInt16(this.write, i >> 8 & 0xFFFF); this.data.setInt8(this.write, i >> 16 & 0xFF); this.write += 3; return this; }; /** * Puts a 32-bit integer in this buffer in big-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt32 = function(i) { this.accommodate(4); this.data.setInt32(this.write, i); this.write += 4; return this; }; /** * Puts a 16-bit integer in this buffer in little-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt16Le = function(i) { this.accommodate(2); this.data.setInt16(this.write, i, true); this.write += 2; return this; }; /** * Puts a 24-bit integer in this buffer in little-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt24Le = function(i) { this.accommodate(3); this.data.setInt8(this.write, i >> 16 & 0xFF); this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); this.write += 3; return this; }; /** * Puts a 32-bit integer in this buffer in little-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt32Le = function(i) { this.accommodate(4); this.data.setInt32(this.write, i, true); this.write += 4; return this; }; /** * Puts an n-bit integer in this buffer in big-endian order. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.DataBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); do { n -= 8; this.data.setInt8(this.write++, (i >> n) & 0xFF); } while(n > 0); return this; }; /** * Puts a signed n-bit integer in this buffer in big-endian order. Two's * complement representation is used. * * @param i the n-bit integer. * @param n the number of bits in the integer. * * @return this buffer. */ util.DataBuffer.prototype.putSignedInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); if(i < 0) { i += 2 << (n - 1); } return this.putInt(i, n); }; /** * Gets a byte from this buffer and advances the read pointer by 1. * * @return the byte. */ util.DataBuffer.prototype.getByte = function() { return this.data.getInt8(this.read++); }; /** * Gets a uint16 from this buffer in big-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.DataBuffer.prototype.getInt16 = function() { var rval = this.data.getInt16(this.read); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in big-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.DataBuffer.prototype.getInt24 = function() { var rval = ( this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2)); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in big-endian order and advances the read * pointer by 4. * * @return the word. */ util.DataBuffer.prototype.getInt32 = function() { var rval = this.data.getInt32(this.read); this.read += 4; return rval; }; /** * Gets a uint16 from this buffer in little-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.DataBuffer.prototype.getInt16Le = function() { var rval = this.data.getInt16(this.read, true); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in little-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.DataBuffer.prototype.getInt24Le = function() { var rval = ( this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in little-endian order and advances the read * pointer by 4. * * @return the word. */ util.DataBuffer.prototype.getInt32Le = function() { var rval = this.data.getInt32(this.read, true); this.read += 4; return rval; }; /** * Gets an n-bit integer from this buffer in big-endian order and advances the * read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.DataBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. rval = (rval << 8) + this.data.getInt8(this.read++); n -= 8; } while(n > 0); return rval; }; /** * Gets a signed n-bit integer from this buffer in big-endian order, using * two's complement, and advances the read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.DataBuffer.prototype.getSignedInt = function(n) { // getInt checks n var x = this.getInt(n); var max = 2 << (n - 2); if(x >= max) { x -= max << 1; } return x; }; /** * Reads bytes out as a binary encoded string and clears them from the * buffer. * * @param count the number of bytes to read, undefined or null for all. * * @return a binary encoded string of bytes. */ util.DataBuffer.prototype.getBytes = function(count) { // TODO: deprecate this method, it is poorly named and // this.toString('binary') replaces it // add a toTypedArray()/toArrayBuffer() function var rval; if(count) { // read count bytes count = Math.min(this.length(), count); rval = this.data.slice(this.read, this.read + count); this.read += count; } else if(count === 0) { rval = ''; } else { // read all bytes, optimize to only copy when needed rval = (this.read === 0) ? this.data : this.data.slice(this.read); this.clear(); } return rval; }; /** * Gets a binary encoded string of the bytes from this buffer without * modifying the read pointer. * * @param count the number of bytes to get, omit to get all. * * @return a string full of binary encoded characters. */ util.DataBuffer.prototype.bytes = function(count) { // TODO: deprecate this method, it is poorly named, add "getString()" return (typeof(count) === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count)); }; /** * Gets a byte at the given index without modifying the read pointer. * * @param i the byte index. * * @return the byte. */ util.DataBuffer.prototype.at = function(i) { return this.data.getUint8(this.read + i); }; /** * Puts a byte at the given index without modifying the read pointer. * * @param i the byte index. * @param b the byte to put. * * @return this buffer. */ util.DataBuffer.prototype.setAt = function(i, b) { this.data.setUint8(i, b); return this; }; /** * Gets the last byte without modifying the read pointer. * * @return the last byte. */ util.DataBuffer.prototype.last = function() { return this.data.getUint8(this.write - 1); }; /** * Creates a copy of this buffer. * * @return the copy. */ util.DataBuffer.prototype.copy = function() { return new util.DataBuffer(this); }; /** * Compacts this buffer. * * @return this buffer. */ util.DataBuffer.prototype.compact = function() { if(this.read > 0) { var src = new Uint8Array(this.data.buffer, this.read); var dst = new Uint8Array(src.byteLength); dst.set(src); this.data = new DataView(dst); this.write -= this.read; this.read = 0; } return this; }; /** * Clears this buffer. * * @return this buffer. */ util.DataBuffer.prototype.clear = function() { this.data = new DataView(new ArrayBuffer(0)); this.read = this.write = 0; return this; }; /** * Shortens this buffer by triming bytes off of the end of this buffer. * * @param count the number of bytes to trim off. * * @return this buffer. */ util.DataBuffer.prototype.truncate = function(count) { this.write = Math.max(0, this.length() - count); this.read = Math.min(this.read, this.write); return this; }; /** * Converts this buffer to a hexadecimal string. * * @return a hexadecimal string. */ util.DataBuffer.prototype.toHex = function() { var rval = ''; for(var i = this.read; i < this.data.byteLength; ++i) { var b = this.data.getUint8(i); if(b < 16) { rval += '0'; } rval += b.toString(16); } return rval; }; /** * Converts this buffer to a string, using the given encoding. If no * encoding is given, 'utf8' (UTF-8) is used. * * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', * 'base64' (default: 'utf8'). * * @return a string representation of the bytes in this buffer. */ util.DataBuffer.prototype.toString = function(encoding) { var view = new Uint8Array(this.data, this.read, this.length()); encoding = encoding || 'utf8'; // encode to string if(encoding === 'binary' || encoding === 'raw') { return util.binary.raw.encode(view); } if(encoding === 'hex') { return util.binary.hex.encode(view); } if(encoding === 'base64') { return util.binary.base64.encode(view); } // decode to text if(encoding === 'utf8') { return util.text.utf8.decode(view); } if(encoding === 'utf16') { return util.text.utf16.decode(view); } throw new Error('Invalid encoding: ' + encoding); }; /** End Buffer w/UInt8Array backing */ /** * Creates a buffer that stores bytes. A value may be given to populate the * buffer with data. This value can either be string of encoded bytes or a * regular string of characters. When passing a string of binary encoded * bytes, the encoding `raw` should be given. This is also the default. When * passing a string of characters, the encoding `utf8` should be given. * * @param [input] a string with encoded bytes to store in the buffer. * @param [encoding] (default: 'raw', other: 'utf8'). */ util.createBuffer = function(input, encoding) { // TODO: deprecate, use new ByteBuffer() instead encoding = encoding || 'raw'; if(input !== undefined && encoding === 'utf8') { input = util.encodeUtf8(input); } return new util.ByteBuffer(input); }; /** * Fills a string with a particular value. If you want the string to be a byte * string, pass in String.fromCharCode(theByte). * * @param c the character to fill the string with, use String.fromCharCode * to fill the string with a byte value. * @param n the number of characters of value c to fill with. * * @return the filled string. */ util.fillString = function(c, n) { var s = ''; while(n > 0) { if(n & 1) { s += c; } n >>>= 1; if(n > 0) { c += c; } } return s; }; /** * Performs a per byte XOR between two byte strings and returns the result as a * string of bytes. * * @param s1 first string of bytes. * @param s2 second string of bytes. * @param n the number of bytes to XOR. * * @return the XOR'd result. */ util.xorBytes = function(s1, s2, n) { var s3 = ''; var b = ''; var t = ''; var i = 0; var c = 0; for(; n > 0; --n, ++i) { b = s1.charCodeAt(i) ^ s2.charCodeAt(i); if(c >= 10) { s3 += t; t = ''; c = 0; } t += String.fromCharCode(b); ++c; } s3 += t; return s3; }; /** * Converts a hex string into a 'binary' encoded string of bytes. * * @param hex the hexadecimal string to convert. * * @return the binary-encoded string of bytes. */ util.hexToBytes = function(hex) { // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." var rval = ''; var i = 0; if(hex.length & 1 == 1) { // odd number of characters, convert first character alone i = 1; rval += String.fromCharCode(parseInt(hex[0], 16)); } // convert 2 characters (1 byte) at a time for(; i < hex.length; i += 2) { rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); } return rval; }; /** * Converts a 'binary' encoded string of bytes to hex. * * @param bytes the byte string to convert. * * @return the string of hexadecimal characters. */ util.bytesToHex = function(bytes) { // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." return util.createBuffer(bytes).toHex(); }; /** * Converts an 32-bit integer to 4-big-endian byte string. * * @param i the integer. * * @return the byte string. */ util.int32ToBytes = function(i) { return ( String.fromCharCode(i >> 24 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; // base64 characters, reverse mapping var _base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var _base64Idx = [ /*43 -43 = 0*/ /*'+', 1, 2, 3,'/' */ 62, -1, -1, -1, 63, /*'0','1','2','3','4','5','6','7','8','9' */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, /*15, 16, 17,'=', 19, 20, 21 */ -1, -1, -1, 64, -1, -1, -1, /*65 - 43 = 22*/ /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, /*91 - 43 = 48 */ /*48, 49, 50, 51, 52, 53 */ -1, -1, -1, -1, -1, -1, /*97 - 43 = 54*/ /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 ]; // base58 characters (Bitcoin alphabet) var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; /** * Base64 encodes a 'binary' encoded string of bytes. * * @param input the binary encoded string of bytes to base64-encode. * @param maxline the maximum number of encoded characters per line to use, * defaults to none. * * @return the base64-encoded output. */ util.encode64 = function(input, maxline) { // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." var line = ''; var output = ''; var chr1, chr2, chr3; var i = 0; while(i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); // encode 4 character group line += _base64.charAt(chr1 >> 2); line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); if(isNaN(chr2)) { line += '=='; } else { line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); } if(maxline && line.length > maxline) { output += line.substr(0, maxline) + '\r\n'; line = line.substr(maxline); } } output += line; return output; }; /** * Base64 decodes a string into a 'binary' encoded string of bytes. * * @param input the base64-encoded input. * * @return the binary encoded string. */ util.decode64 = function(input) { // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." // remove all non-base64 characters input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); var output = ''; var enc1, enc2, enc3, enc4; var i = 0; while(i < input.length) { enc1 = _base64Idx[input.charCodeAt(i++) - 43]; enc2 = _base64Idx[input.charCodeAt(i++) - 43]; enc3 = _base64Idx[input.charCodeAt(i++) - 43]; enc4 = _base64Idx[input.charCodeAt(i++) - 43]; output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); if(enc3 !== 64) { // decoded at least 2 bytes output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); if(enc4 !== 64) { // decoded 3 bytes output += String.fromCharCode(((enc3 & 3) << 6) | enc4); } } } return output; }; /** * Encodes the given string of characters (a standard JavaScript * string) as a binary encoded string where the bytes represent * a UTF-8 encoded string of characters. Non-ASCII characters will be * encoded as multiple bytes according to UTF-8. * * @param str a standard string of characters to encode. * * @return the binary encoded string. */ util.encodeUtf8 = function(str) { return unescape(encodeURIComponent(str)); }; /** * Decodes a binary encoded string that contains bytes that * represent a UTF-8 encoded string of characters -- into a * string of characters (a standard JavaScript string). * * @param str the binary encoded string to decode. * * @return the resulting standard string of characters. */ util.decodeUtf8 = function(str) { return decodeURIComponent(escape(str)); }; // binary encoding/decoding tools // FIXME: Experimental. Do not use yet. util.binary = { raw: {}, hex: {}, base64: {}, base58: {}, baseN : { encode: baseN.encode, decode: baseN.decode } }; /** * Encodes a Uint8Array as a binary-encoded string. This encoding uses * a value between 0 and 255 for each character. * * @param bytes the Uint8Array to encode. * * @return the binary-encoded string. */ util.binary.raw.encode = function(bytes) { return String.fromCharCode.apply(null, bytes); }; /** * Decodes a binary-encoded string to a Uint8Array. This encoding uses * a value between 0 and 255 for each character. * * @param str the binary-encoded string to decode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.raw.decode = function(str, output, offset) { var out = output; if(!out) { out = new Uint8Array(str.length); } offset = offset || 0; var j = offset; for(var i = 0; i < str.length; ++i) { out[j++] = str.charCodeAt(i); } return output ? (j - offset) : out; }; /** * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or * ByteBuffer as a string of hexadecimal characters. * * @param bytes the bytes to convert. * * @return the string of hexadecimal characters. */ util.binary.hex.encode = util.bytesToHex; /** * Decodes a hex-encoded string to a Uint8Array. * * @param hex the hexadecimal string to convert. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.hex.decode = function(hex, output, offset) { var out = output; if(!out) { out = new Uint8Array(Math.ceil(hex.length / 2)); } offset = offset || 0; var i = 0, j = offset; if(hex.length & 1) { // odd number of characters, convert first character alone i = 1; out[j++] = parseInt(hex[0], 16); } // convert 2 characters (1 byte) at a time for(; i < hex.length; i += 2) { out[j++] = parseInt(hex.substr(i, 2), 16); } return output ? (j - offset) : out; }; /** * Base64-encodes a Uint8Array. * * @param input the Uint8Array to encode. * @param maxline the maximum number of encoded characters per line to use, * defaults to none. * * @return the base64-encoded output string. */ util.binary.base64.encode = function(input, maxline) { var line = ''; var output = ''; var chr1, chr2, chr3; var i = 0; while(i < input.byteLength) { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[i++]; // encode 4 character group line += _base64.charAt(chr1 >> 2); line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); if(isNaN(chr2)) { line += '=='; } else { line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); } if(maxline && line.length > maxline) { output += line.substr(0, maxline) + '\r\n'; line = line.substr(maxline); } } output += line; return output; }; /** * Decodes a base64-encoded string to a Uint8Array. * * @param input the base64-encoded input string. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.base64.decode = function(input, output, offset) { var out = output; if(!out) { out = new Uint8Array(Math.ceil(input.length / 4) * 3); } // remove all non-base64 characters input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); offset = offset || 0; var enc1, enc2, enc3, enc4; var i = 0, j = offset; while(i < input.length) { enc1 = _base64Idx[input.charCodeAt(i++) - 43]; enc2 = _base64Idx[input.charCodeAt(i++) - 43]; enc3 = _base64Idx[input.charCodeAt(i++) - 43]; enc4 = _base64Idx[input.charCodeAt(i++) - 43]; out[j++] = (enc1 << 2) | (enc2 >> 4); if(enc3 !== 64) { // decoded at least 2 bytes out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); if(enc4 !== 64) { // decoded 3 bytes out[j++] = ((enc3 & 3) << 6) | enc4; } } } // make sure result is the exact decoded length return output ? (j - offset) : out.subarray(0, j); }; // add support for base58 encoding/decoding with Bitcoin alphabet util.binary.base58.encode = function(input, maxline) { return util.binary.baseN.encode(input, _base58, maxline); }; util.binary.base58.decode = function(input, maxline) { return util.binary.baseN.decode(input, _base58, maxline); }; // text encoding/decoding tools // FIXME: Experimental. Do not use yet. util.text = { utf8: {}, utf16: {} }; /** * Encodes the given string as UTF-8 in a Uint8Array. * * @param str the string to encode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.text.utf8.encode = function(str, output, offset) { str = util.encodeUtf8(str); var out = output; if(!out) { out = new Uint8Array(str.length); } offset = offset || 0; var j = offset; for(var i = 0; i < str.length; ++i) { out[j++] = str.charCodeAt(i); } return output ? (j - offset) : out; }; /** * Decodes the UTF-8 contents from a Uint8Array. * * @param bytes the Uint8Array to decode. * * @return the resulting string. */ util.text.utf8.decode = function(bytes) { return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); }; /** * Encodes the given string as UTF-16 in a Uint8Array. * * @param str the string to encode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.text.utf16.encode = function(str, output, offset) { var out = output; if(!out) { out = new Uint8Array(str.length * 2); } var view = new Uint16Array(out.buffer); offset = offset || 0; var j = offset; var k = offset; for(var i = 0; i < str.length; ++i) { view[k++] = str.charCodeAt(i); j += 2; } return output ? (j - offset) : out; }; /** * Decodes the UTF-16 contents from a Uint8Array. * * @param bytes the Uint8Array to decode. * * @return the resulting string. */ util.text.utf16.decode = function(bytes) { return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); }; /** * Deflates the given data using a flash interface. * * @param api the flash interface. * @param bytes the data. * @param raw true to return only raw deflate data, false to include zlib * header and trailer. * * @return the deflated data as a string. */ util.deflate = function(api, bytes, raw) { bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); // strip zlib header and trailer if necessary if(raw) { // zlib header is 2 bytes (CMF,FLG) where FLG indicates that // there is a 4-byte DICT (alder-32) block before the data if // its 5th bit is set var start = 2; var flg = bytes.charCodeAt(1); if(flg & 0x20) { start = 6; } // zlib trailer is 4 bytes of adler-32 bytes = bytes.substring(start, bytes.length - 4); } return bytes; }; /** * Inflates the given data using a flash interface. * * @param api the flash interface. * @param bytes the data. * @param raw true if the incoming data has no zlib header or trailer and is * raw DEFLATE data. * * @return the inflated data as a string, null on error. */ util.inflate = function(api, bytes, raw) { // TODO: add zlib header and trailer if necessary/possible var rval = api.inflate(util.encode64(bytes)).rval; return (rval === null) ? null : util.decode64(rval); }; /** * Sets a storage object. * * @param api the storage interface. * @param id the storage ID to use. * @param obj the storage object, null to remove. */ var _setStorageObject = function(api, id, obj) { if(!api) { throw new Error('WebStorage not available.'); } var rval; if(obj === null) { rval = api.removeItem(id); } else { // json-encode and base64-encode object obj = util.encode64(JSON.stringify(obj)); rval = api.setItem(id, obj); } // handle potential flash error if(typeof(rval) !== 'undefined' && rval.rval !== true) { var error = new Error(rval.error.message); error.id = rval.error.id; error.name = rval.error.name; throw error; } }; /** * Gets a storage object. * * @param api the storage interface. * @param id the storage ID to use. * * @return the storage object entry or null if none exists. */ var _getStorageObject = function(api, id) { if(!api) { throw new Error('WebStorage not available.'); } // get the existing entry var rval = api.getItem(id); /* Note: We check api.init because we can't do (api == localStorage) on IE because of "Class doesn't support Automation" exception. Only the flash api has an init method so this works too, but we need a better solution in the future. */ // flash returns item wrapped in an object, handle special case if(api.init) { if(rval.rval === null) { if(rval.error) { var error = new Error(rval.error.message); error.id = rval.error.id; error.name = rval.error.name; throw error; } // no error, but also no item rval = null; } else { rval = rval.rval; } } // handle decoding if(rval !== null) { // base64-decode and json-decode data rval = JSON.parse(util.decode64(rval)); } return rval; }; /** * Stores an item in local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. * @param data the data for the item (any javascript object/primitive). */ var _setItem = function(api, id, key, data) { // get storage object var obj = _getStorageObject(api, id); if(obj === null) { // create a new storage object obj = {}; } // update key obj[key] = data; // set storage object _setStorageObject(api, id, obj); }; /** * Gets an item from local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. * * @return the item. */ var _getItem = function(api, id, key) { // get storage object var rval = _getStorageObject(api, id); if(rval !== null) { // return data at key rval = (key in rval) ? rval[key] : null; } return rval; }; /** * Removes an item from local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. */ var _removeItem = function(api, id, key) { // get storage object var obj = _getStorageObject(api, id); if(obj !== null && key in obj) { // remove key delete obj[key]; // see if entry has no keys remaining var empty = true; for(var prop in obj) { empty = false; break; } if(empty) { // remove entry entirely if no keys are left obj = null; } // set storage object _setStorageObject(api, id, obj); } }; /** * Clears the local disk storage identified by the given ID. * * @param api the storage interface. * @param id the storage ID to use. */ var _clearItems = function(api, id) { _setStorageObject(api, id, null); }; /** * Calls a storage function. * * @param func the function to call. * @param args the arguments for the function. * @param location the location argument. * * @return the return value from the function. */ var _callStorageFunction = function(func, args, location) { var rval = null; // default storage types if(typeof(location) === 'undefined') { location = ['web', 'flash']; } // apply storage types in order of preference var type; var done = false; var exception = null; for(var idx in location) { type = location[idx]; try { if(type === 'flash' || type === 'both') { if(args[0] === null) { throw new Error('Flash local storage not available.'); } rval = func.apply(this, args); done = (type === 'flash'); } if(type === 'web' || type === 'both') { args[0] = localStorage; rval = func.apply(this, args); done = true; } } catch(ex) { exception = ex; } if(done) { break; } } if(!done) { throw exception; } return rval; }; /** * Stores an item on local disk. * * The available types of local storage include 'flash', 'web', and 'both'. * * The type 'flash' refers to flash local storage (SharedObject). In order * to use flash local storage, the 'api' parameter must be valid. The type * 'web' refers to WebStorage, if supported by the browser. The type 'both' * refers to storing using both 'flash' and 'web', not just one or the * other. * * The location array should list the storage types to use in order of * preference: * * ['flash']: flash only storage * ['web']: web only storage * ['both']: try to store in both * ['flash','web']: store in flash first, but if not available, 'web' * ['web','flash']: store in web first, but if not available, 'flash' * * The location array defaults to: ['web', 'flash'] * * @param api the flash interface, null to use only WebStorage. * @param id the storage ID to use. * @param key the key for the item. * @param data the data for the item (any javascript object/primitive). * @param location an array with the preferred types of storage to use. */ util.setItem = function(api, id, key, data, location) { _callStorageFunction(_setItem, arguments, location); }; /** * Gets an item on local disk. * * Set setItem() for details on storage types. * * @param api the flash interface, null to use only WebStorage. * @param id the storage ID to use. * @param key the key for the item. * @param location an array with the preferred types of storage to use. * * @return the item. */ util.getItem = function(api, id, key, location) { return _callStorageFunction(_getItem, arguments, location); }; /** * Removes an item on local disk. * * Set setItem() for details on storage types. * * @param api the flash interface. * @param id the storage ID to use. * @param key the key for the item. * @param location an array with the preferred types of storage to use. */ util.removeItem = function(api, id, key, location) { _callStorageFunction(_removeItem, arguments, location); }; /** * Clears the local disk storage identified by the given ID. * * Set setItem() for details on storage types. * * @param api the flash interface if flash is available. * @param id the storage ID to use. * @param location an array with the preferred types of storage to use. */ util.clearItems = function(api, id, location) { _callStorageFunction(_clearItems, arguments, location); }; /** * Check if an object is empty. * * Taken from: * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 * * @param object the object to check. */ util.isEmpty = function(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)) { return false; } } return true; }; /** * Format with simple printf-style interpolation. * * %%: literal '%' * %s,%o: convert next argument into a string. * * @param format the string to format. * @param ... arguments to interpolate into the format string. */ util.format = function(format) { var re = /%./g; // current match var match; // current part var part; // current arg index var argi = 0; // collected parts to recombine later var parts = []; // last index found var last = 0; // loop while matches remain while((match = re.exec(format))) { part = format.substring(last, re.lastIndex - 2); // don't add empty strings (ie, parts between %s%s) if(part.length > 0) { parts.push(part); } last = re.lastIndex; // switch on % code var code = match[0][1]; switch(code) { case 's': case 'o': // check if enough arguments were given if(argi < arguments.length) { parts.push(arguments[argi++ + 1]); } else { parts.push('<?>'); } break; // FIXME: do proper formating for numbers, etc //case 'f': //case 'd': case '%': parts.push('%'); break; default: parts.push('<%' + code + '?>'); } } // add trailing part of format string parts.push(format.substring(last)); return parts.join(''); }; /** * Formats a number. * * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ */ util.formatNumber = function(number, decimals, dec_point, thousands_sep) { // http://kevin.vanzonneveld.net // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfix by: Michael White (http://crestidg.com) // + bugfix by: Benjamin Lupton // + bugfix by: Allan Jensen (http://www.winternet.no) // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // * example 1: number_format(1234.5678, 2, '.', ''); // * returns 1: 1234.57 var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; var d = dec_point === undefined ? ',' : dec_point; var t = thousands_sep === undefined ? '.' : thousands_sep, s = n < 0 ? '-' : ''; var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; var j = (i.length > 3) ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); }; /** * Formats a byte size. * * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ */ util.formatSize = function(size) { if(size >= 1073741824) { size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; } else if(size >= 1048576) { size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; } else if(size >= 1024) { size = util.formatNumber(size / 1024, 0) + ' KiB'; } else { size = util.formatNumber(size, 0) + ' bytes'; } return size; }; /** * Converts an IPv4 or IPv6 string representation into bytes (in network order). * * @param ip the IPv4 or IPv6 address to convert. * * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't * be parsed. */ util.bytesFromIP = function(ip) { if(ip.indexOf('.') !== -1) { return util.bytesFromIPv4(ip); } if(ip.indexOf(':') !== -1) { return util.bytesFromIPv6(ip); } return null; }; /** * Converts an IPv4 string representation into bytes (in network order). * * @param ip the IPv4 address to convert. * * @return the 4-byte address or null if the address can't be parsed. */ util.bytesFromIPv4 = function(ip) { ip = ip.split('.'); if(ip.length !== 4) { return null; } var b = util.createBuffer(); for(var i = 0; i < ip.length; ++i) { var num = parseInt(ip[i], 10); if(isNaN(num)) { return null; } b.putByte(num); } return b.getBytes(); }; /** * Converts an IPv6 string representation into bytes (in network order). * * @param ip the IPv6 address to convert. * * @return the 16-byte address or null if the address can't be parsed. */ util.bytesFromIPv6 = function(ip) { var blanks = 0; ip = ip.split(':').filter(function(e) { if(e.length === 0) ++blanks; return true; }); var zeros = (8 - ip.length + blanks) * 2; var b = util.createBuffer(); for(var i = 0; i < 8; ++i) { if(!ip[i] || ip[i].length === 0) { b.fillWithByte(0, zeros); zeros = 0; continue; } var bytes = util.hexToBytes(ip[i]); if(bytes.length < 2) { b.putByte(0); } b.putBytes(bytes); } return b.getBytes(); }; /** * Converts 4-bytes into an IPv4 string representation or 16-bytes into * an IPv6 string representation. The bytes must be in network order. * * @param bytes the bytes to convert. * * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, * respectively, are given, otherwise null. */ util.bytesToIP = function(bytes) { if(bytes.length === 4) { return util.bytesToIPv4(bytes); } if(bytes.length === 16) { return util.bytesToIPv6(bytes); } return null; }; /** * Converts 4-bytes into an IPv4 string representation. The bytes must be * in network order. * * @param bytes the bytes to convert. * * @return the IPv4 string representation or null for an invalid # of bytes. */ util.bytesToIPv4 = function(bytes) { if(bytes.length !== 4) { return null; } var ip = []; for(var i = 0; i < bytes.length; ++i) { ip.push(bytes.charCodeAt(i)); } return ip.join('.'); }; /** * Converts 16-bytes into an IPv16 string representation. The bytes must be * in network order. * * @param bytes the bytes to convert. * * @return the IPv16 string representation or null for an invalid # of bytes. */ util.bytesToIPv6 = function(bytes) { if(bytes.length !== 16) { return null; } var ip = []; var zeroGroups = []; var zeroMaxGroup = 0; for(var i = 0; i < bytes.length; i += 2) { var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); // canonicalize zero representation while(hex[0] === '0' && hex !== '0') { hex = hex.substr(1); } if(hex === '0') { var last = zeroGroups[zeroGroups.length - 1]; var idx = ip.length; if(!last || idx !== last.end + 1) { zeroGroups.push({start: idx, end: idx}); } else { last.end = idx; if((last.end - last.start) > (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { zeroMaxGroup = zeroGroups.length - 1; } } } ip.push(hex); } if(zeroGroups.length > 0) { var group = zeroGroups[zeroMaxGroup]; // only shorten group of length > 0 if(group.end - group.start > 0) { ip.splice(group.start, group.end - group.start + 1, ''); if(group.start === 0) { ip.unshift(''); } if(group.end === 7) { ip.push(''); } } } return ip.join(':'); }; /** * Estimates the number of processes that can be run concurrently. If * creating Web Workers, keep in mind that the main JavaScript process needs * its own core. * * @param options the options to use: * update true to force an update (not use the cached value). * @param callback(err, max) called once the operation completes. */ util.estimateCores = function(options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options = options || {}; if('cores' in util && !options.update) { return callback(null, util.cores); } if(typeof navigator !== 'undefined' && 'hardwareConcurrency' in navigator && navigator.hardwareConcurrency > 0) { util.cores = navigator.hardwareConcurrency; return callback(null, util.cores); } if(typeof Worker === 'undefined') { // workers not available util.cores = 1; return callback(null, util.cores); } if(typeof Blob === 'undefined') { // can't estimate, default to 2 util.cores = 2; return callback(null, util.cores); } // create worker concurrency estimation code as blob var blobUrl = URL.createObjectURL(new Blob(['(', function() { self.addEventListener('message', function(e) { // run worker for 4 ms var st = Date.now(); var et = st + 4; while(Date.now() < et); self.postMessage({st: st, et: et}); }); }.toString(), ')()'], {type: 'application/javascript'})); // take 5 samples using 16 workers sample([], 5, 16); function sample(max, samples, numWorkers) { if(samples === 0) { // get overlap average var avg = Math.floor(max.reduce(function(avg, x) { return avg + x; }, 0) / max.length); util.cores = Math.max(1, avg); URL.revokeObjectURL(blobUrl); return callback(null, util.cores); } map(numWorkers, function(err, results) { max.push(reduce(numWorkers, results)); sample(max, samples - 1, numWorkers); }); } function map(numWorkers, callback) { var workers = []; var results = []; for(var i = 0; i < numWorkers; ++i) { var worker = new Worker(blobUrl); worker.addEventListener('message', function(e) { results.push(e.data); if(results.length === numWorkers) { for(var i = 0; i < numWorkers; ++i) { workers[i].terminate(); } callback(null, results); } }); workers.push(worker); } for(var i = 0; i < numWorkers; ++i) { workers[i].postMessage(i); } } function reduce(numWorkers, results) { // find overlapping time windows var overlaps = []; for(var n = 0; n < numWorkers; ++n) { var r1 = results[n]; var overlap = overlaps[n] = []; for(var i = 0; i < numWorkers; ++i) { if(n === i) { continue; } var r2 = results[i]; if((r1.st > r2.st && r1.st < r2.et) || (r2.st > r1.st && r2.st < r1.et)) { overlap.push(i); } } } // get maximum overlaps ... don't include overlapping worker itself // as the main JS process was also being scheduled during the work and // would have to be subtracted from the estimate anyway return overlaps.reduce(function(max, overlap) { return Math.max(max, overlap.length); }, 0); } };
test.js
it("testGcm", ()=>{ var key = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]); var iv = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4]); // var key = Buffer.from(keys); // console.log(key); // var iv = Buffer.from(ivs); var x = new gcm({key:key}); x.start({iv:iv}); var input = "123456"; var inputBufferOut = forge.util.createBuffer(input); console.log(inputBufferOut.toHex()); var inputBuffer = forge.util.createBuffer(input); var outputBuffer = forge.util.createBuffer(); for (var i = inputBuffer.length(); i>0; i = i - 16 ){ if (i > 16){ x.encrypt(inputBuffer, outputBuffer, false); } else{ x.encrypt(inputBuffer, outputBuffer, true); } } x.afterFinish(outputBuffer, {}) console.log(outputBuffer.toHex()) console.log(x.tag.toHex()) const n = outputBuffer.toHex() + x.tag.toHex(); const m = n.slice(0, n.length - x.tag.toHex().length); console.log(m); const outputBytes = forge.util.hexToBytes(m); const outputBuffer2 = forge.util.createBuffer(outputBytes); const tags: any = x.tag; var y = new gcm({key:key}); y.start({iv:iv,decrypt:true,tag:tags.getBytes()}) var plainBuffer = forge.util.createBuffer(); for (var i = outputBuffer2.length(); i>0; i = i - 16 ){ if (i > 16){ y.decrypt(outputBuffer2, plainBuffer, false); } else{ y.decrypt(outputBuffer2, plainBuffer, true); } console.log(plainBuffer.length()) } var result = y.afterFinish(plainBuffer, {decrypt:true}) console.log(y.tag.toHex()) console.log(result) console.log(plainBuffer.toHex()) const hex = plainBuffer.toHex().slice(0, inputBufferOut.toHex().length) console.log(hex) const arr = [] for (let i = 0, len = hex.length; i < len; i += 2) { arr.push(parseInt(hex.substr(i, 2), 16)) } const str = [] for (let i = 0, len = arr.length; i < len; i++) { if (arr[i] >= 0xf0 && arr[i] <= 0xf7) { // 四字节 str.push(String.fromCodePoint(((arr[i] & 0x07) << 18) + ((arr[i + 1] & 0x3f) << 12) + ((arr[i + 2] & 0x3f) << 6) + (arr[i + 3] & 0x3f))) i += 3 } else if (arr[i] >= 0xe0 && arr[i] <= 0xef) { // 三字节 str.push(String.fromCodePoint(((arr[i] & 0x0f) << 12) + ((arr[i + 1] & 0x3f) << 6) + (arr[i + 2] & 0x3f))) i += 2 } else if (arr[i] >= 0xc0 && arr[i] <= 0xdf) { // 双字节 str.push(String.fromCodePoint(((arr[i] & 0x1f) << 6) + (arr[i + 1] & 0x3f))) i++ } else { // 单字节 str.push(String.fromCodePoint(arr[i])) } } console.log(str.join('')); })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。