random_bytes( int $bytes )

Windows with PHP < 5.3.0 will not have the function openssl_random_pseudo_bytes() available, so let's use CAPICOM to work around this deficiency.


Description Description


Parameters Parameters

$bytes

(int) (Required)


Top ↑

Return Return

(string)


Top ↑

Source Source

File: wp-includes/random_compat/random_bytes_com_dotnet.php

    function random_bytes($bytes)
    {
        try {
            $bytes = RandomCompat_intval($bytes);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_bytes(): $bytes must be an integer'
            );
        }

        if ($bytes < 1) {
            throw new Error(
                'Length must be greater than 0'
            );
        }

        $buf = '';
        if (!class_exists('COM')) {
            throw new Error(
                'COM does not exist'
            );
        }
        $util = new COM('CAPICOM.Utilities.1');
        $execCount = 0;

        /**
         * Let's not let it loop forever. If we run N times and fail to
         * get N bytes of random data, then CAPICOM has failed us.
         */
        do {
            $buf .= base64_decode($util->GetRandom($bytes, 0));
            if (RandomCompat_strlen($buf) >= $bytes) {
                /**
                 * Return our random entropy buffer here:
                 */
                return RandomCompat_substr($buf, 0, $bytes);
            }
            ++$execCount;
        } while ($execCount < $bytes);

        /**
         * If we reach here, PHP has failed us.
         */
        throw new Exception(
            'Could not gather sufficient random data'
        );
    }


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.