Exemplo n.º 1
0
 /**
  * The code for this function was translated to PHP from mcrypt's enigma.c,
  * I was not able to find sufficient documentation to create my own
  * version of this function.
  * Enigma requires a 13 byte key, this function will
  * lengthen the key to get it to 13 bytes long if it's short. It also
  * Sets $deck, and $t1, $t2, $t3 which I think are the Enigma rotors.
  *
  * @return void
  */
 private function createKey()
 {
     $this->deck = array();
     $this->t1 = array();
     $this->t2 = array_fill(0, self::ROTORSZ, 0);
     $this->t3 = $this->t2;
     $this->xkey = $this->key();
     $klen = $this->keySize();
     // get the key to exactly 13 bytes if it's less than 13
     if ($klen < 13) {
         $this->xkey = str_pad($this->xkey, 13, chr(0), STR_PAD_RIGHT);
     }
     $seed = 123;
     for ($i = 0; $i < 13; ++$i) {
         $seed = parent::sInt32($seed) * ord($this->xkey[$i]) + $i;
     }
     // sets $t1 and $deck
     for ($i = 0; $i < self::ROTORSZ; ++$i) {
         $this->t1[] = $i;
         $this->deck[] = $i;
     }
     // sets $t3
     for ($i = 0; $i < self::ROTORSZ; ++$i) {
         // make sure the return values are 32 bit
         $seed = 5 * parent::sInt32($seed) + ord($this->xkey[$i % 13]);
         $seed = parent::sInt32($seed);
         // force the returned value to be an unsigned int
         //$random = parent::uint32($seed % 65521);
         $random = parent::uInt($seed % 65521);
         $k = self::ROTORSZ - 1 - $i;
         $ic = ($random & self::MASK) % ($k + 1);
         // make sure the returned value is an unsigned int
         $random = parent::uInt($random >> 8);
         $temp = $this->t1[$k];
         $this->t1[$k] = $this->t1[$ic];
         $this->t1[$ic] = $temp;
         if ($this->t3[$k] != 0) {
             continue;
         }
         $ic = ($random & self::MASK) % $k;
         while ($this->t3[$ic] != 0) {
             $ic = ($ic + 1) % $k;
         }
         $this->t3[$k] = $ic;
         $this->t3[$ic] = $k;
     }
     // sets $t2
     for ($i = 0; $i < self::ROTORSZ; ++$i) {
         $pos = $this->t1[$i] & self::MASK;
         $this->t2[$pos] = $i;
     }
     // now convert $t1, $t2, $t3, $deck values to signed chars,
     // PHP's chr() function returns an unsigned char, so we have
     // to use use our own
     $this->t1 = array_map("parent::sChar", $this->t1);
     $this->t2 = array_map("parent::sChar", $this->t2);
     $this->t3 = array_map("parent::sChar", $this->t3);
     $this->deck = array_map("parent::sChar", $this->deck);
 }