This is really all I changed; making scryptsy a state machine so we occasionally stop and give other evnts on the evnt loop a chance to run. ~RicMoo
482583
function() {
            if (stop) {
                return callback(new Error('cancelled'), currentOp / totalOps);
            }

            switch (state) {
                case 0:
                    // for (var i = 0; i < p; i++)...
                    Bi = i0 * 32 * r;

                    arraycopy(B, Bi, XY, 0, Yi);                       // ROMix - 1

                    state = 1;                                         // Move to ROMix 2
                    i1 = 0;

                    // Fall through

                case 1:

                    // Run up to 1000 steps of the first inner smix loop
                    var steps = N - i1;
                    if (steps > limit) { steps = limit; }
                    for (var i = 0; i < steps; i++) {                  // ROMix - 2
                        arraycopy(XY, 0, V, (i1 + i) * Yi, Yi)         // ROMix - 3
                        blockmix_salsa8(XY, Yi, r, x, _X);             // ROMix - 4
                    }

                    // for (var i = 0; i < N; i++)
                    i1 += steps;
                    currentOp += steps;

                    // Call the callback with the progress (optionally stopping us)
                    var percent10 = parseInt(1000 * currentOp / totalOps);
                    if (percent10 !== lastPercent10) {
                        stop = callback(null, currentOp / totalOps);
                        if (stop) { break; }
                        lastPercent10 = percent10;
                    }

                    if (i1 < N) {
                        break;
                    }

                    i1 = 0;                                          // Move to ROMix 6
                    state = 2;

                    // Fall through

                case 2:

                    // Run up to 1000 steps of the second inner smix loop
                    var steps = N - i1;
                    if (steps > limit) { steps = limit; }
                    for (var i = 0; i < steps; i++) {                // ROMix - 6
                        var offset = (2 * r - 1) * 16;               // ROMix - 7
                        var j = XY[offset] & (N - 1);
                        blockxor(V, j * Yi, XY, Yi);                 // ROMix - 8 (inner)
                        blockmix_salsa8(XY, Yi, r, x, _X);           // ROMix - 9 (outer)
                    }

                    // for (var i = 0; i < N; i++)...
                    i1 += steps;
                    currentOp += steps;

                    // Call the callback with the progress (optionally stopping us)
                    var percent10 = parseInt(1000 * currentOp / totalOps);
                    if (percent10 !== lastPercent10) {
                        stop = callback(null, currentOp / totalOps);
                        if (stop) { break; }
                        lastPercent10 = percent10;
                    }

                    if (i1 < N) {
                        break;
                    }

                    arraycopy(XY, 0, B, Bi, Yi);                     // ROMix - 10

                    // for (var i = 0; i < p; i++)...
                    i0++;
                    if (i0 < p) {
                        state = 0;
                        break;
                    }

                    b = [];
                    for (var i = 0; i < B.length; i++) {
                        b.push((B[i] >>  0) & 0xff);
                        b.push((B[i] >>  8) & 0xff);
                        b.push((B[i] >> 16) & 0xff);
                        b.push((B[i] >> 24) & 0xff);
                    }

                    var derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen);

                    // Done; don't break (which would reschedule)
                    return callback(null, 1.0, derivedKey);
                }

                // Schedule the next steps
                nextTick(incrementalSMix);
            }
450103
function create() {
  var sha1sum = crypto.createHash('sha1');
  return { update: update, digest: digest };

  function update(data) {
    sha1sum.update(data);
  }

  function digest() {
    return sha1sum.digest('hex');
  }
}
679059
function SessionCipher(crypto) {
    const self = this;

    const ratchet = new Ratchet(crypto);

    /**
     * Encrypt a message using the session.
     * <p>
     * If this method succeeds, the passed in session should be destroyed. This method must never be called with
     * that session again.
     *
     * @method
     * @param {Session} session
     * @param {ArrayBuffer} message - the message bytes to be encrypted (optionally padded)
     * @return {Promise.<Object, Error>} an object containing the encrypted message bytes as well as a new session
     */
    this.encryptMessage = co.wrap(function*(session, message) {
        var newSession = new Session(session);
        var whisperMessage = yield createWhisperMessage(newSession, message);

        yield ratchet.clickSubRatchet(newSession.mostRecentState().sendingChain);

        if (newSession.mostRecentState().pendingPreKey) {
            return {
                isPreKeyWhisperMessage: true,
                body: createPreKeyWhisperMessage(newSession, whisperMessage),
                session: newSession
            };
        } else {
            return {
                isPreKeyWhisperMessage: false,
                body: whisperMessage,
                session: newSession
            };
        }
    });

    /**
     * Unwrap the WhisperMessage from a PreKeyWhisperMessage and attempt to decrypt it using session.
     *
     * @method
     * @param {Session} session
     * @param {ArrayBuffer} preKeyWhisperMessageBytes
     * @returns {Promise.<Object, InvalidMessageException>} an object containing the decrypted message and a new session
     */
    this.decryptPreKeyWhisperMessage = (session, preKeyWhisperMessageBytes) => {
        var preKeyWhisperMessage = Messages.decodePreKeyWhisperMessage(preKeyWhisperMessageBytes);
        return self.decryptWhisperMessage(session, preKeyWhisperMessage.message.message);
    };

    /**
     * Decrypt a WhisperMessage using session.
     * <p>
     * If this method succeeds, the passed in session should be destroyed. This method must never be called with
     * that session again.
     *
     * @method
     * @param {Session} session
     * @param {ArrayBuffer} whisperMessageBytes - the encrypted message bytes
     * @returns {Promise.<Object, InvalidMessageException>} an object containing the decrypted message and a new session
     */
    this.decryptWhisperMessage = co.wrap(function*(session, whisperMessageBytes) {
        var newSession = new Session(session);
        var exceptions = [];
        for (var state of newSession.states) {
            var clonedSessionState = new SessionState(state);
            var promise = decryptWhisperMessageWithSessionState(clonedSessionState, whisperMessageBytes);
            var result = yield promise.catch((e) => {
                exceptions.push(e);
            });
            if (result !== undefined) {
                newSession.removeState(state);
                newSession.addState(clonedSessionState);
                return {
                    message: result,
                    session: newSession
                };
            }
        }
        var messages = exceptions.map((e) => e.toString());
        throw new InvalidMessageException("Unable to decrypt message: " + messages);
    });

    /**
     * Attempt to decrypt a WhisperMessage using sessionState.
     * <p>
     * Failure of this method is not necessarily fatal as it may be possible to decrypt the message using another
     * session state.
     *
     * @method
     * @private
     * @param {SessionState} sessionState
     * @param {ArrayBuffer} whisperMessageBytes
     * @returns {Promise.<ArrayBuffer, InvalidMessageException>}
     */
    var decryptWhisperMessageWithSessionState = co.wrap(function*(sessionState, whisperMessageBytes) {
        var whisperMessage = Messages.decodeWhisperMessage(whisperMessageBytes);
        var macInputTypes = Messages.decodeWhisperMessageMacInput(whisperMessageBytes);

        if (whisperMessage.version.current !== sessionState.sessionVersion) {
            throw new InvalidMessageException("Message version doesn't match session version");
        }

        var message = whisperMessage.message;
        var theirEphemeralPublicKey = message.ratchetKey;

        var receivingChain = yield getOrCreateReceivingChain(sessionState, theirEphemeralPublicKey);
        var messageKeys = yield getOrCreateMessageKeys(theirEphemeralPublicKey, receivingChain, message.counter);
        var isValid = yield isValidMac(macInputTypes, messageKeys.macKey, whisperMessage.version.current,
            sessionState.remoteIdentityKey, sessionState.localIdentityKey, whisperMessage.mac);

        if (!isValid) {
            throw new InvalidMessageException("Bad mac");
        }

        // TODO: Support for version 2: Use CTR mode instead of CBC
        var plaintext = yield crypto.decrypt(messageKeys.cipherKey, message.ciphertext, messageKeys.iv);

        sessionState.pendingPreKey = null;

        return plaintext;
    });

    /**
     * Verifies the MAC of a WhisperMessage.
     *
     * @method
     * @private
     * @param {ArrayBuffer} data - the data to calculate the MAC over
     * @param {ArrayBuffer} macKey - the MAC key
     * @param {number} messageVersion
     * @param {ArrayBuffer} senderIdentityKey
     * @param {ArrayBuffer} receiverIdentityKey
     * @param {ArrayBuffer} theirMac - the MAC to check
     * @return {Promise.<Boolean, Error>} true if theirMac is valid, false otherwise.
     */
    var isValidMac = co.wrap(function*(data, macKey, messageVersion, senderIdentityKey, receiverIdentityKey, theirMac) {
        var ourMac = yield getMac(data, macKey, messageVersion, senderIdentityKey, receiverIdentityKey);
        return ArrayBufferUtils.areEqual(ourMac, theirMac);
    });

    /**
     * Calculate the MAC of a WhisperMessage.
     *
     * @method
     * @private
     * @param {ArrayBuffer} data - the data to calculate the MAC over
     * @param {ArrayBuffer} macKey - the MAC key
     * @param {number} messageVersion
     * @param {ArrayBuffer} senderIdentityKey
     * @param {ArrayBuffer} receiverIdentityKey
     * @return {Promise.<ArrayBuffer, Error>} the MAC bytes.
     */
    var getMac = co.wrap(function*(data, macKey, messageVersion, senderIdentityKey, receiverIdentityKey) {
        var macInputs = (messageVersion >= 3) ? [senderIdentityKey, receiverIdentityKey] : [];
        macInputs.push(data);
        var macBytes = yield crypto.hmac(macKey, ArrayBufferUtils.concat(macInputs));
        return macBytes.slice(0, ProtocolConstants.macByteCount);
    });

    /**
     * Create an encrypted WhisperMessage.
     *
     * @method
     * @private
     * @param {Session} session
     * @param {ArrayBuffer} paddedMessage
     * @return {Promise.<ArrayBuffer, Error>} the bytes of an encoded WhisperMessage
     */
    var createWhisperMessage = co.wrap(function*(session, paddedMessage) {
        var messageKeys = yield ratchet.deriveMessageKeys(session.mostRecentState().sendingChain.key);
        // TODO: Should use CTR mode in version 2 of protocol
        var ciphertext = yield crypto.encrypt(messageKeys.cipherKey, paddedMessage, messageKeys.iv);

        var version = {
            current: session.mostRecentState().sessionVersion,
            max: ProtocolConstants.currentVersion
        };
        var message = {
            ratchetKey: session.mostRecentState().senderRatchetKeyPair.public,
            counter: session.mostRecentState().sendingChain.index,
            previousCounter: session.mostRecentState().previousCounter,
            ciphertext: ciphertext
        };
        var macInputBytes = Messages.encodeWhisperMessageMacInput({
            version: version,
            message: message
        });

        return Messages.encodeWhisperMessage({
            version: version,
            message: message,
            mac: yield getMac(macInputBytes, messageKeys.macKey, session.mostRecentState().sessionVersion,
                session.mostRecentState().localIdentityKey,
                session.mostRecentState().remoteIdentityKey)
        });
    });

    /**
     * Create an encrypted PreKeyWhisperMessage.
     *
     * @method
     * @private
     * @param {Session} session
     * @param {ArrayBuffer} whisperMessage - the bytes of an encoded WhisperMessage
     * @return {Promise.<ArrayBuffer, Error>} the bytes of an encoded PreKeyWhisperMessage
     */
    var createPreKeyWhisperMessage = (session, whisperMessage) => {
        var pendingPreKey = session.mostRecentState().pendingPreKey;
        return Messages.encodePreKeyWhisperMessage({
            version: {
                current: session.mostRecentState().sessionVersion,
                max: ProtocolConstants.currentVersion
            },
            message: {
                registrationId: session.mostRecentState().localRegistrationId,
                preKeyId: pendingPreKey.preKeyId,
                signedPreKeyId: pendingPreKey.signedPreKeyId,
                baseKey: pendingPreKey.baseKey,
                identityKey: session.mostRecentState().localIdentityKey,
                message: whisperMessage
            }
        });
    };

    /**
     * Find the chain for decryption that corresponds to the ephemeral key sent in their message.
     * <p>
     * This method handles stepping the main ratchet, if necessary.
     *
     * @method
     * @private
     * @param {SessionState} sessionState
     * @param {ArrayBuffer} theirEphemeralPublicKey - the ephemeral key sent in the message.
     * @return {Promise.<Chain, Error>} the receiving chain
     */
    var getOrCreateReceivingChain = co.wrap(function*(sessionState, theirEphemeralPublicKey) {
        // If they've sent us multiple messages before receiving a reply from us, then those messages will be sent using
        // the same ephemeral key (i.e. the main ratchet will not click forward).
        var chain = sessionState.findReceivingChain(theirEphemeralPublicKey);
        if (chain) {
            return chain;
        }
        // This is the first message in a new chain.
        return yield clickMainRatchet(sessionState, theirEphemeralPublicKey);
    });

    /**
     * Find the message keys for decryption that correspond to the ephemeral key sent in their message.
     * <p>
     * This method handles stepping the sub ratchet, if necessary.
     *
     * @method
     * @private
     * @param {ArrayBuffer} theirEphemeralPublicKey - the ephemeral key sent in the message.
     * @param {Chain} chain - the chain for decryption.
     * @param {number} counter - the counter sent in the message.
     * @return {Promise.<MessageKeys, Error>} the message keys for decryption
     */
    var getOrCreateMessageKeys = co.wrap(function*(theirEphemeralPublicKey, chain, counter) {
        if (chain.index > counter) {
            // The message is an old message that has been delivered out of order. We should still have the message
            // key cached unless this is a duplicate message that we've seen before.
            var cachedMessageKeys = chain.messageKeys[counter];
            if (!cachedMessageKeys) {
                throw new DuplicateMessageException("Received message with old counter");
            }
            // We don't want to be able to decrypt this message again, for forward secrecy.
            delete chain.messageKeys[counter];
            return cachedMessageKeys;
        } else {
            // Otherwise, the message is a new message in the chain and we must click the sub ratchet forwards.
            if (counter - chain.index > ProtocolConstants.maximumMissedMessages) {
                throw new InvalidMessageException("Too many skipped messages");
            }
            while (chain.index < counter) {
                // Some messages have not yet been delivered ("skipped") and so we need to catch the sub ratchet up
                // while keeping the message keys for when the messages are eventually delivered.
                chain.messageKeys[chain.index] = yield ratchet.deriveMessageKeys(chain.key);
                yield ratchet.clickSubRatchet(chain);
            }
            var messageKeys = yield ratchet.deriveMessageKeys(chain.key);
            // As we have received the message, we should click the sub ratchet forwards so we can't decrypt it again
            yield ratchet.clickSubRatchet(chain);
            return messageKeys;
        }
    });

    /**
     * "clicks" the Diffie-Hellman ratchet two steps forwards. Once to catch up with the other party and once
     * more so that the next message we send will be one ahead.
     *
     * @method
     * @private
     * @param {SessionState} sessionState
     * @param {ArrayBuffer} theirEphemeralPublicKey
     * @return {Promise.<Chain, Error>} the next chain for decryption
     */
    var clickMainRatchet = co.wrap(function*(sessionState, theirEphemeralPublicKey) {
        var {
            rootKey: theirRootKey,
            chain: nextReceivingChain
        } = yield ratchet.deriveNextRootKeyAndChain(sessionState.rootKey, theirEphemeralPublicKey,
                sessionState.senderRatchetKeyPair.private);
        var ourNewEphemeralKeyPair = yield crypto.generateKeyPair();
        var {
            rootKey,
            chain: nextSendingChain
        } = yield ratchet.deriveNextRootKeyAndChain(theirRootKey,
                theirEphemeralPublicKey, ourNewEphemeralKeyPair.private);
        sessionState.rootKey = rootKey;
        sessionState.addReceivingChain(theirEphemeralPublicKey, nextReceivingChain);
        sessionState.previousCounter = Math.max(sessionState.sendingChain.index - 1, 0);
        sessionState.sendingChain = nextSendingChain;
        sessionState.senderRatchetKeyPair = ourNewEphemeralKeyPair;
        return nextReceivingChain;
    });

    Object.freeze(self);
}
895186
def run(self):
        
        states = open(self.states, 'r').read().splitlines()
        for state in states:
            url = self.build_url(state)
            log = "Downloading State < {0} > from < {1} >"
            logging.info(log.format(state, url))
            tmp = self.download(self.output, url, self.overwrite)
            self.s3.store(self.extract(tmp, self.tmp2poi(tmp)))
571471
function () {
        this.stage++;

        var that = this;
        //logger.log('send_nonce called');

        CryptoLib.getRandomBytes(Handshake.NONCE_BYTES, function (ex, buf) {

            that.nonce = buf;
            that.socket.write(buf);

//            if (buf) {
//                logger.log("sent nonce ", buf.toString('hex'));
//            }

            //a good start
            that.nextStep();
        });

    }
1006910
function _seed() {
    // create a plugin-based message digest
    var md = ctx.plugin.md.create();

    // digest pool 0's entropy and restart it
    md.update(ctx.pools[0].digest().getBytes());
    ctx.pools[0].start();

    // digest the entropy of other pools whose index k meet the
    // condition '2^k mod n == 0' where n is the number of reseeds
    var k = 1;
    for(var i = 1; i < 32; ++i) {
      // prevent signed numbers from being used
      k = (k === 31) ? 0x80000000 : (k << 2);
      if(k % ctx.reseeds === 0) {
        md.update(ctx.pools[i].digest().getBytes());
        ctx.pools[i].start();
      }
    }

    // get digest for key bytes and iterate again for seed bytes
    var keyBytes = md.digest().getBytes();
    md.start();
    md.update(keyBytes);
    var seedBytes = md.digest().getBytes();

    // update
    ctx.key = ctx.plugin.formatKey(keyBytes);
    ctx.seed = ctx.plugin.formatSeed(seedBytes);
    ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;
    ctx.generated = 0;
  }
1354700
function scrypt(password, salt, N, r, p, dkLen, callback) {

        if (!callback) { throw new Error('missing callback'); }

        N = ensureInteger(N, 'N');
        r = ensureInteger(r, 'r');
        p = ensureInteger(p, 'p');

        dkLen = ensureInteger(dkLen, 'dkLen');

        if (N === 0 || (N & (N - 1)) !== 0) { throw new Error('N must be power of 2'); }

        if (N > MAX_VALUE / 128 / r) { throw new Error('N too large'); }
        if (r > MAX_VALUE / 128 / p) { throw new Error('r too large'); }

        if (!checkBufferish(password)) {
            throw new Error('password must be an array or buffer');
        }
        password = Array.prototype.slice.call(password);

        if (!checkBufferish(salt)) {
            throw new Error('salt must be an array or buffer');
        }
        salt = Array.prototype.slice.call(salt);

        var b = PBKDF2_HMAC_SHA256_OneIter(password, salt, p * 128 * r);
        var B = new Uint32Array(p * 32 * r)
        for (var i = 0; i < B.length; i++) {
            var j = i * 4;
            B[i] = ((b[j + 3] & 0xff) << 24) |
                   ((b[j + 2] & 0xff) << 16) |
                   ((b[j + 1] & 0xff) << 8) |
                   ((b[j + 0] & 0xff) << 0);
        }

        var XY = new Uint32Array(64 * r);
        var V = new Uint32Array(32 * r * N);

        var Yi = 32 * r;

        // scratch space
        var x = new Uint32Array(16);       // salsa20_8
        var _X = new Uint32Array(16);      // blockmix_salsa8

        var totalOps = p * N * 2;
        var currentOp = 0;
        var lastPercent10 = null;

        // Set this to true to abandon the scrypt on the next step
        var stop = false;

        // State information
        var state = 0;
        var i0 = 0, i1;
        var Bi;

        // How many blockmix_salsa8 can we do per step?
        var limit = parseInt(1000 / r);

        // Trick from scrypt-async; if there is a setImmediate shim in place, use it
        var nextTick = (typeof(setImmediate) !== 'undefined') ? setImmediate : setTimeout;

        // This is really all I changed; making scryptsy a state machine so we occasionally
        // stop and give other evnts on the evnt loop a chance to run. ~RicMoo
        var incrementalSMix = function() {
            if (stop) {
                return callback(new Error('cancelled'), currentOp / totalOps);
            }

            switch (state) {
                case 0:
                    // for (var i = 0; i < p; i++)...
                    Bi = i0 * 32 * r;

                    arraycopy(B, Bi, XY, 0, Yi);                       // ROMix - 1

                    state = 1;                                         // Move to ROMix 2
                    i1 = 0;

                    // Fall through

                case 1:

                    // Run up to 1000 steps of the first inner smix loop
                    var steps = N - i1;
                    if (steps > limit) { steps = limit; }
                    for (var i = 0; i < steps; i++) {                  // ROMix - 2
                        arraycopy(XY, 0, V, (i1 + i) * Yi, Yi)         // ROMix - 3
                        blockmix_salsa8(XY, Yi, r, x, _X);             // ROMix - 4
                    }

                    // for (var i = 0; i < N; i++)
                    i1 += steps;
                    currentOp += steps;

                    // Call the callback with the progress (optionally stopping us)
                    var percent10 = parseInt(1000 * currentOp / totalOps);
                    if (percent10 !== lastPercent10) {
                        stop = callback(null, currentOp / totalOps);
                        if (stop) { break; }
                        lastPercent10 = percent10;
                    }

                    if (i1 < N) {
                        break;
                    }

                    i1 = 0;                                          // Move to ROMix 6
                    state = 2;

                    // Fall through

                case 2:

                    // Run up to 1000 steps of the second inner smix loop
                    var steps = N - i1;
                    if (steps > limit) { steps = limit; }
                    for (var i = 0; i < steps; i++) {                // ROMix - 6
                        var offset = (2 * r - 1) * 16;               // ROMix - 7
                        var j = XY[offset] & (N - 1);
                        blockxor(V, j * Yi, XY, Yi);                 // ROMix - 8 (inner)
                        blockmix_salsa8(XY, Yi, r, x, _X);           // ROMix - 9 (outer)
                    }

                    // for (var i = 0; i < N; i++)...
                    i1 += steps;
                    currentOp += steps;

                    // Call the callback with the progress (optionally stopping us)
                    var percent10 = parseInt(1000 * currentOp / totalOps);
                    if (percent10 !== lastPercent10) {
                        stop = callback(null, currentOp / totalOps);
                        if (stop) { break; }
                        lastPercent10 = percent10;
                    }

                    if (i1 < N) {
                        break;
                    }

                    arraycopy(XY, 0, B, Bi, Yi);                     // ROMix - 10

                    // for (var i = 0; i < p; i++)...
                    i0++;
                    if (i0 < p) {
                        state = 0;
                        break;
                    }

                    b = [];
                    for (var i = 0; i < B.length; i++) {
                        b.push((B[i] >>  0) & 0xff);
                        b.push((B[i] >>  8) & 0xff);
                        b.push((B[i] >> 16) & 0xff);
                        b.push((B[i] >> 24) & 0xff);
                    }

                    var derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen);

                    // Done; don't break (which would reschedule)
                    return callback(null, 1.0, derivedKey);
                }

                // Schedule the next steps
                nextTick(incrementalSMix);
            }

            // Bootstrap the incremental smix
            incrementalSMix();
    }
420179
function (password, opts) {
        /*jshint maxcomplexity:17 */

        opts = opts || {};
        var salt = opts.salt || cryptoUtils.crypto.randomBytes(32);
        var iv = opts.iv || cryptoUtils.crypto.randomBytes(16);
        var derivedKey;
        var kdf = opts.kdf || 'scrypt';
        var kdfparams = {
            dklen: opts.dklen || 32,
            salt: salt.toString('hex')
        };
        if (kdf === 'pbkdf2') {
            kdfparams.c = opts.c || 262144;
            kdfparams.prf = 'hmac-sha256';
            derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256');
        } else if (kdf === 'scrypt') {
            kdfparams.n = opts.n || 4096;
            kdfparams.r = opts.r || 8;
            kdfparams.p = opts.p || 1;
            derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
        } else {
            throw new Error('Unsupported kdf');
        }
        var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv);
        if (!cipher) {
            throw new Error('Unsupported cipher');
        }
        var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]);
        // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')]));   // KeyVersion3 deprecated
        var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')]));
        return {
            version: KeyCurrentVersion,
            id: cryptoUtils.uuid.v4({
                random: opts.uuid || cryptoUtils.crypto.randomBytes(16)
            }),
            address: this.getAddressString(),
            crypto: {
                ciphertext: ciphertext.toString('hex'),
                cipherparams: {
                    iv: iv.toString('hex')
                },
                cipher: opts.cipher || 'aes-128-ctr',
                kdf: kdf,
                kdfparams: kdfparams,
                mac: mac.toString('hex'),
                machash: "sha3256"
            }
        };
    }
601255
def fixup_prngs():
    
    s = os.urandom(256 // 8)
    random.seed(s)
    if 'ssl' in sys.modules:
        sys.modules['ssl'].RAND_add(s, 75.0)
384626
function (input, dir) {
    if (input.length !== 4) {
      throw new sjcl.exception.invalid("invalid aes block size");
    }

    var key = this._key[dir],
        // state variables a,b,c,d are loaded with pre-whitened data
        a = input[0]           ^ key[0],
        b = input[dir ? 3 : 1] ^ key[1],
        c = input[2]           ^ key[2],
        d = input[dir ? 1 : 3] ^ key[3],
        a2, b2, c2,

        nInnerRounds = key.length/4 - 2,
        i,
        kIndex = 4,
        out = [0,0,0,0],
        table = this._tables[dir],

        // load up the tables
        t0    = table[0],
        t1    = table[1],
        t2    = table[2],
        t3    = table[3],
        sbox  = table[4];

    // Inner rounds.  Cribbed from OpenSSL.
    for (i = 0; i < nInnerRounds; i++) {
      a2 = t0[a>>>24] ^ t1[b>>16 & 255] ^ t2[c>>8 & 255] ^ t3[d & 255] ^ key[kIndex];
      b2 = t0[b>>>24] ^ t1[c>>16 & 255] ^ t2[d>>8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
      c2 = t0[c>>>24] ^ t1[d>>16 & 255] ^ t2[a>>8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
      d  = t0[d>>>24] ^ t1[a>>16 & 255] ^ t2[b>>8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
      kIndex += 4;
      a=a2; b=b2; c=c2;
    }

    // Last round.
    for (i = 0; i < 4; i++) {
      out[dir ? 3&-i : i] =
        sbox[a>>>24      ]<<24 ^
        sbox[b>>16  & 255]<<16 ^
        sbox[c>>8   & 255]<<8  ^
        sbox[d      & 255]     ^
        key[kIndex++];
      a2=a; a=b; b=c; c=d; d=a2;
    }

    return out;
  }
862804
function cloneState(state) {
  return {
    options: state.options,
    stack: state.stack.slice(),
    nodes: state.nodes.slice()
  };
}
852287
function StateMachine(name) {
        var _this = _super.call(this, name, undefined) || this;
        /** Internal flag: false if the state machine model requires recompilation. */
        /** @internal */ _this.clean = false;
        return _this;
    }
1064953
function generateRandomBytes (size, attempts, callback) {
  crypto.randomBytes(size, function onRandomBytes (err, buf) {
    if (!err) return callback(null, buf)
    if (!--attempts) return callback(err)
    setTimeout(generateRandomBytes.bind(null, size, attempts, callback), 10)
  })
}
985109
def transition_running_state(target_state)
      state_transitions = {
        not_started: :running,
        running: :stopping,
        stopping: :stopped
      }
      if state_transitions[@running_state] == target_state
        @running_state = target_state
      else
        fail "Bad server state transition: #{@running_state}->#{target_state}"
      end
    end
1304717
def backward_step(self):
        
        logger.debug("Executing backward step ...")
        self.run_to_states = []
        self.set_execution_mode(StateMachineExecutionStatus.BACKWARD)
1227513
function roll(data, checksums, blockSize) {
  var results = [];
  var hashtable = createHashtable(checksums);
  var length = data.length;
  var start = 0;
  var end = blockSize > length ? length : blockSize;
  // Updated when a block matches
  var lastMatchedEnd = 0;
  // This gets updated every iteration with the previous weak 32bit hash
  var prevRollingWeak = null;
  var weak;
  var weak16;
  var match;
  var d;
  var len;
  var mightMatch;
  var chunk;
  var strong;
  var hashtable_weak16;
  var hashtable_weak16i;

  for (; end <= length; start++, end++) {
    weak = calcWeak32(data, prevRollingWeak, start, end);
    weak16 = calcWeak16(weak.sum);
    match = false;
    d = null;
    prevRollingWeak = weak;
    hashtable_weak16 = hashtable[weak16];

    if (hashtable_weak16) {
      len = hashtable_weak16.length;
      for (var i = 0; i < len; i++) {
        hashtable_weak16i = hashtable_weak16[i];
        if (hashtable_weak16i.weak === weak.sum) {
          mightMatch = hashtable_weak16i;
          chunk = data.slice(start, end);
          strong = md5sum(chunk);

          if (mightMatch.strong === strong) {
            match = mightMatch;
            break;
          }
        }
      }
    }
    if (match) {
      if(start < lastMatchedEnd) {
        d = data.slice(lastMatchedEnd - 1, end);
        results.push({
          data: d,
          index: match.index
        });
      } else if (start - lastMatchedEnd > 0) {
        d = data.slice(lastMatchedEnd, start);
        results.push({
          data: d,
          index: match.index
        });
      } else {
        results.push({
          index: match.index
        });
      }
      lastMatchedEnd = end;
    } else if (end === length) {
      // No match and last block
      d = data.slice(lastMatchedEnd);
      results.push({
        data: d
      });
    }
  }
  return results;
}
1214784
public void stateMachine(ShanksSimulation sim) throws Exception{
        logger.fine("Using default state machine for ScenarioManager");
//        switch (this.simulationStateMachineStatus) {
//        case CHECK_FAILURES:
//            this.checkFailures(sim);
//            this.simulationStateMachineStatus = GENERATE_FAILURES;
//            break;
//        case GENERATE_FAILURES:
//            this.generateFailures(sim);
//            this.simulationStateMachineStatus = CHECK_PERIODIC_;
//            break;
//        case GENERATE_PERIODIC_EVENTS:
//            this.generatePeriodicEvents(sim);
//            this.simulationStateMachineStatus = CHECK_FAILURES;
//            break;
//        case GENERATE_RANDOM_EVENTS:
//            this.generateRandomEvents(sim);
//            this.simulationStateMachineStatus = CHECK_FAILURES;
//            break;
//        }

        this.checkFailures(sim);
        this.generateFailures(sim);
        this.generateScenarioEvents(sim);
        this.generateNetworkElementEvents(sim);
        long step = sim.getSchedule().getSteps();
        if (step%500==0) {
            logger.info("Step: " + step);
            logger.finest("In step " + step + ", there are " + sim.getScenario().getCurrentFailures().size() + " current failures.");
            logger.finest("In step " + step + ", there are " + sim.getNumOfResolvedFailures() + " resolved failures.");
        }
    }