Generates a RSA public/private keypair

@param int $keyBits (optional) The number of key bits to use. Can be: 1024, 2048, 4096
@return array Returns an associative array with 'public' and 'private' keys
429473
public static function _generateRSAKeys($keyBits = 2048) {
        $conf = array(
            'digest_alg' => 'sha256',
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
            'private_key_bits' => $keyBits,
            'encrypt_key' => true,
        );


        $res = openssl_pkey_new($conf);
        $keys = array();
        openssl_pkey_export($res, $keys['private']);
        $publickey = openssl_pkey_get_details($res);
        $keys['public'] = $publickey["key"];
        return($keys);
    }
245569
def make_rsa_keypair(bits):
    
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
        backend=default_backend(),
    )
    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    public_pem = private_key.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    return private_pem, public_pem
1284213
public function decryptByPrivateKey_data($data, $privatekey = '')
	{
		$RSACrypt = new RSACrypt();

		if ($privatekey != "") {  // if null use default
			$RSACrypt->privkey = $privatekey;
		}
		$decrypt_res = "";
		$datas = explode('@', $data);
		foreach ($datas as $value) {
			$decrypt_res = $decrypt_res . $RSACrypt->decryptByPrivateKey($value);
		}
		return $decrypt_res;
	}
1261368
public static function createRSAKey(int $size, array $values = []): JWK
    {
        if (0 !== $size % 8) {
            throw new InvalidArgumentException('Invalid key size.');
        }

        if (512 > $size) {
            throw new InvalidArgumentException('Key length is too short. It needs to be at least 512 bits.');
        }

        $key = openssl_pkey_new([
            'private_key_bits' => $size,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ]);
        $details = openssl_pkey_get_details($key);
        \openssl_free_key($key);
        $rsa = RSAKey::createFromKeyDetails($details['rsa']);
        $values = \array_merge(
            $values,
            $rsa->toArray()
        );

        return new JWK($values);
    }
690066
public static function tones2Bits($tones) {
    	$bits = 0;
    	if (empty($tones)) {
return 0;}
    	foreach ($tones as $tone) {
    		$bits += pow(2, $tone);
    	}
    	return $bits;
    }
1051343
public function decodeBitwise($bitwise)
    {
        $result = [];

        foreach ($this->bitwise as $key => $value) {
            $result[$key] = ((($bitwise >> $value) & 1) == 1);
        }

        $this->fill($result);

        return $this;
    }
384945
private function generateNonce($bits = 64)
    {
        $result          = '';
        $accumulatedBits = 0;
        $random          = mt_getrandmax();

        for ($totalBits = 0; $random != 0; $random >>= 1) {
            ++$totalBits;
        }

        $usableBits = intval($totalBits / 8) * 8;

        while ($accumulatedBits < $bits) {
            $bitsToAdd = min($totalBits - $usableBits, $bits - $accumulatedBits);
            if ($bitsToAdd % 4 != 0) {
                // add bits in whole increments of 4
                $bitsToAdd += 4 - $bitsToAdd % 4;
            }

            // isolate leftmost $bits_to_add from mt_rand() result
            $moreBits = mt_rand() & ((1 << $bitsToAdd) - 1);

            // format as hex (this will be safe)
            $format_string = '%0'.($bitsToAdd / 4).'x';
            $result .= sprintf($format_string, $moreBits);
            $accumulatedBits += $bitsToAdd;
        }

        return $result;
    }
483142
function _generateMinMax($bits)
    {
        $bytes = $bits >> 3;
        $min = str_repeat(chr(0), $bytes);
        $max = str_repeat(chr(0xFF), $bytes);
        $msb = $bits & 7;
        if ($msb) {
            $min = chr(1 << ($msb - 1)) . $min;
            $max = chr((1 << $msb) - 1) . $max;
        } else {
            $min[0] = chr(0x80);
        }

        return array(
            'min' => new Math_BigInteger($min, 256),
            'max' => new Math_BigInteger($max, 256)
        );
    }
1169513
public function write_bits($bits)
    {
        $value = 0;

        foreach ($bits as $n => $bit) {
            $bit = $bit ? 1 : 0;
            $value |= ($bit << $n);
        }

        $this->out .= chr($value);

        return $this;
    }
1161098
public function generateKeyPair($keyOption = null)
    {
        if (null === $keyOption) {
            $keyOption = new RsaKeyOption();
        }
        if (\is_int($keyOption)) {
            @trigger_error('Passing a keySize to "generateKeyPair" is deprecated since version 1.1 and will be removed in 2.0. Pass an instance of KeyOption instead', E_USER_DEPRECATED);
            $keyOption = new RsaKeyOption($keyOption);
        }
        Assert::isInstanceOf($keyOption, KeyOption::class);

        try {
            $privateKey = $this->generator->generatePrivateKey($keyOption);
        } catch (KeyGenerationException $e) {
            throw new KeyPairGenerationException('Fail to generate a KeyPair with the given options', 0, $e);
        }

        return new KeyPair(
            $privateKey->getPublicKey(),
            $privateKey
        );
    }
678785
public function generateKey(array $options = array())
	{
		// Create the new encryption key[/pair] object.
		$key = new Key('simple');

		// Just a random key of a given length.
		$key->private = $this->_getRandomKey();
		$key->public  = $key->private;

		return $key;
	}
754374
public static function loadKeyFromX509Resource($res): array
    {
        $key = \openssl_get_publickey($res);

        $details = \openssl_pkey_get_details($key);
        if (isset($details['key'])) {
            $values = self::loadKeyFromPEM($details['key']);
            \openssl_x509_export($res, $out);
            $x5c = \preg_replace('#-.*-#', '', $out);
            $x5c = \preg_replace('~\R~', PHP_EOL, $x5c);
            $x5c = \trim($x5c);
            $values['x5c'] = [$x5c];

            $values['x5t'] = Base64Url::encode(\openssl_x509_fingerprint($res, 'sha1', true));
            $values['x5t#256'] = Base64Url::encode(\openssl_x509_fingerprint($res, 'sha256', true));

            return $values;
        }

        throw new \InvalidArgumentException('Unable to load the certificate');
    }
561422
private function getKeyPair()
    {
        $config = $this->app->make('config/database');

        // Seee if we already have a kypair
        $keyPair = $config->get('api.keypair');

        if (!$keyPair) {
            $rsa = $this->app->make(RSA::class);

            // Generate a new RSA key
            $keyPair = $rsa->createKey(2048);

            foreach ($keyPair as &$item) {
                $item = str_replace("\r\n", "\n", $item);
            }

            // Save the keypair
            $config->save('api.keypair', $keyPair);
        }

        return $keyPair;
    }
788052
private function generatePrivateECKey(): JWK
    {
        return JWKFactory::createFromKeyFile($this->privateKeyPath, $this->privateKeySecret, [
            'kid' => $this->keyId,
            'alg' => 'ES512',
            'use' => 'sig'
        ]);
    }
1209078
public static function generateIdentityKeyPair()
    {
        $keyPair = Curve::generateKeyPair();
        $publicKey = new IdentityKey($keyPair->getPublicKey());
        $serialized = '0a21056e8936e8367f768a7bba008ade7cf58407bdc7a6aae293e2cb7c06668dcd7d5e12205011524f0c15467100dd6'.
                     '03e0d6020f4d293edfbcd82129b14a88791ac81365c';
        $serialized = pack('H*', $serialized);
        $identityKeyPair = new IdentityKeyPair($publicKey, $keyPair->getPrivateKey());

        return $identityKeyPair;
        // return new IdentityKeyPair(serialized=serialized)
    }
89842
public static function invertBits($n){
		$bits = \floor(\log($n, 2)) + 1;
		$mask = (1 << $bits) - 1;
		return $n ^ $mask;
	}
1007596
public function createSecret($bits = 80, $requirecryptosecure = true)
    {
        $secret = '';
        $bytes = ceil($bits / 5);   //We use 5 bits of each byte (since we have a 32-character 'alphabet' / BASE32)
        $rngprovider = $this->getRngprovider();
        if ($requirecryptosecure && !$rngprovider->isCryptographicallySecure())
            throw new TwoFactorAuthException('RNG provider is not cryptographically secure');
        $rnd = $rngprovider->getRandomBytes($bytes);
        for ($i = 0; $i < $bytes; $i++)
            $secret .= self::$_base32[ord($rnd[$i]) & 31];  //Mask out left 3 bits for 0-31 values
        return $secret;
    }