You are here

public function XMLSecurityKey::generateSessionKey in SAML SP 2.0 Single Sign On (SSO) - SAML Service Provider 7

Generates a session key using the openssl-extension or using the mcrypt-extension as a fallback. In case of using DES3-CBC the key is checked for a proper parity bits set - Mcrypt doesn't care about the parity bits, but others may care.

Return value

string

Throws

Exception

File

includes/XMLSecurityKey.php, line 280

Class

XMLSecurityKey

Code

public function generateSessionKey() {
  if (!isset($this->cryptParams['keysize'])) {
    throw new Exception('Unknown key size for type "' . $this->type . '".');
  }
  $keysize = $this->cryptParams['keysize'];
  if (function_exists('openssl_random_pseudo_bytes')) {

    /* We have PHP >= 5.3 - use openssl to generate session key. */
    $key = openssl_random_pseudo_bytes($keysize);
  }
  else {

    /* Generating random key using iv generation routines */
    $key = mcrypt_create_iv($keysize, MCRYPT_RAND);
  }
  if ($this->type === self::TRIPLEDES_CBC) {

    /* Make sure that the generated key has the proper parity bits set.
     * Mcrypt doesn't care about the parity bits, but others may care.
     */
    for ($i = 0; $i < strlen($key); $i++) {
      $byte = ord($key[$i]) & 0xfe;
      $parity = 1;
      for ($j = 1; $j < 8; $j++) {
        $parity ^= $byte >> $j & 1;
      }
      $byte |= $parity;
      $key[$i] = chr($byte);
    }
  }
  $this->key = $key;
  return $key;
}