phpseclib\Crypt\RC2::setKey PHP Method

setKey() public method

Keys can be of any length. RC2, itself, uses 8 to 1024 bit keys (eg. strlen($key) <= 128), however, we only use the first 128 bytes if $key has more then 128 bytes in it, and set $key to a single null byte if it is empty.
See also: phpseclib\Crypt\Common\SymmetricKey::setKey()
public setKey ( string $key, integer $t1 = false )
$key string
$t1 integer optional Effective key length in bits.
    function setKey($key, $t1 = false)
    {
        $this->orig_key = $key;
        if ($t1 === false) {
            $t1 = $this->default_key_length;
        }
        if ($t1 < 1 || $t1 > 1024) {
            throw new \LengthException('Key size of ' . $length . ' bits is not supported by this algorithm. Only keys between 1 and 1024 bits, inclusive, are supported');
        }
        $this->current_key_length = $t1;
        if (strlen($key) < 1 || strlen($key) > 128) {
            throw new \LengthException('Key of size ' . strlen($key) . ' not supported by this algorithm. Only keys of sizes between 8 and 1024 bits, inclusive, are supported');
        }
        $t = strlen($key);
        // The mcrypt RC2 implementation only supports effective key length
        // of 1024 bits. It is however possible to handle effective key
        // lengths in range 1..1024 by expanding the key and applying
        // inverse pitable mapping to the first byte before submitting it
        // to mcrypt.
        // Key expansion.
        $l = array_values(unpack('C*', $key));
        $t8 = $t1 + 7 >> 3;
        $tm = 0xff >> 8 * $t8 - $t1;
        // Expand key.
        $pitable = $this->pitable;
        for ($i = $t; $i < 128; $i++) {
            $l[$i] = $pitable[$l[$i - 1] + $l[$i - $t]];
        }
        $i = 128 - $t8;
        $l[$i] = $pitable[$l[$i] & $tm];
        while ($i--) {
            $l[$i] = $pitable[$l[$i + 1] ^ $l[$i + $t8]];
        }
        // Prepare the key for mcrypt.
        $l[0] = $this->invpitable[$l[0]];
        array_unshift($l, 'C*');
        $this->key = call_user_func_array('pack', $l);
        $this->key_length = strlen($this->key);
        $this->changed = true;
        $this->_setEngine();
    }

Usage Example

Exemplo n.º 1
0
 /**
  * @dataProvider engineVectors
  */
 public function testVectors($engine, $engineName, $key, $keyLen, $plaintext, $ciphertext)
 {
     $rc2 = new RC2();
     $rc2->disablePadding();
     $rc2->setKeyLength($keyLen);
     $rc2->setKey(pack('H*', $key));
     // could also do $rc2->setKey(pack('H*', $key), $keyLen)
     if (!$rc2->isValidEngine($engine)) {
         self::markTestSkipped('Unable to initialize ' . $engineName . ' engine');
     }
     $rc2->setPreferredEngine($engine);
     $result = bin2hex($rc2->encrypt(pack('H*', $plaintext)));
     $this->assertEquals($result, $ciphertext, "Failed asserting that {$plaintext} yielded expected output in {$engineName} engine");
 }