$A->kexRequest();
$A->send('Hello there!');
$B->send('Hi!');
print "\nSetting up MITM:\n\n";
$state = 0;
$stolenP = null;
$evilShared = null;
$A = new ConversationEntity('A', $dh);
$B = new ConversationEntity('B', $dh);
$A->onSend = function ($data) use($B, &$state, &$stolenP, &$evilShared, $dh) {
    if ($state === 0) {
        print "M: Manipulating kex req\n";
        $obj = json_decode($data);
        $obj->A = $obj->p;
        $stolenP = gmp_init($obj->p, 16);
        $evilShared = gmp_strval($dh->generateShared($stolenP, $stolenP), 16);
        $state = 1;
        $B->receive(json_encode($obj));
    } else {
        $key = sha1($evilShared, true);
        $iv = substr($data, 0, 16);
        $message = decryptAES128CBC(substr($data, 16), $key, $iv);
        print "M: sniffed: {$message}\n";
    }
};
$B->onSend = function ($data) use($A, &$state, &$stolenP, &$evilShared) {
    if ($state === 1) {
        print "M: Manipulating kex resp\n";
        $obj = json_decode($data);
        $obj->B = gmp_strval($stolenP, 16);
        $state = 2;
    }
    function generateShared($private, $public)
    {
        return gmp_powm($public, $private, $this->p);
    }
    function p()
    {
        return gmp_strval($this->p, 16);
    }
    function g($val = null)
    {
        if (is_string($val)) {
            $this->g = gmp_init($val, 16);
        }
        return gmp_strval($this->g, 16);
    }
}
// don't output if we're included into another script.
if (!debug_backtrace()) {
    $dh = new DH();
    $a = $dh->generatePrivate();
    $b = $dh->generatePrivate();
    $A = $dh->generatePublic($a);
    $B = $dh->generatePublic($b);
    $s = $dh->generateShared($a, $B);
    $s2 = $dh->generateShared($b, $A);
    print "A and B shared secrets match:\n";
    print gmp_cmp($s, $s2) === 0 ? "Yes!\n\n" : "No :(\n\n";
    print "Shared secret:\n";
    print gmp_strval($s, 16) . "\n\n";
}