Jake
Jake

Reputation: 26117

Generate 128 bit hex number

I would like to generate a random 128 bit hex number in PHP.

How can I do that?

Upvotes: 3

Views: 9654

Answers (4)

Nick Bedford
Nick Bedford

Reputation: 4435

As of PHP 7, random_bytes is the best method of generating random data, but you can use the random_compat library to add forward-compatible support for random_bytes() to older versions of the language. This library defines the function based on the best fallback method, including the otherwise mentioned openssl_random_pseudo_bytes().

// generates 64-character (256-bit) key
function generate_256bit() {
    return bin2hex(random_bytes(32));
}

// generates 32-character (128-bit) key
function generate_128bit() {
    return bin2hex(random_bytes(16));
}

// 256-bit: f3af82d0bedc3a91b3b5a51beefe553e33a17912de45d3302ed0216ad867cd55
// 128-bit: 4d7245e2d61cfcce2feafd7e687cdb0e

Upvotes: 3

danorton
danorton

Reputation: 12015

As of PHP 5.3:

$rand128_hex = bin2hex(openssl_random_pseudo_bytes(16));

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173572

The simplest I know of:

$str = openssl_random_pseudo_bytes(16);

You can also build a string of 16 characters by appending the character at every loop:

for ($i = 0; $i != 16; ++$i) {
    $str .= chr(mt_rand(0, 255));
}

To turn it into hex, use bin2hex($str). Alternatively, generate a UUID v4 as described in an earlier answer I wrote.

Upvotes: 4

Core Xii
Core Xii

Reputation: 6441

<?php
function string_random($characters, $length)
    {
    $string = '';
    for ($max = mb_strlen($characters) - 1, $i = 0; $i < $length; ++ $i)
        {
        $string .= mb_substr($characters, mt_rand(0, $max), 1);
        }
    return $string;
    }

// 128 bits is 16 bytes; 2 hex digits to represent each byte
$random_128_bit_hex = string_random('0123456789abcdef', 32);
// $random_128_bit_hex might be: '4374e7bb02ae5d5bc6d0d85af78aa2ce'

Upvotes: 0

Related Questions