Christian Giacomi

Random hex strings

Posted — Jun 18, 2018

As a developer is sometimes happens that I need to generate some random bytes as a hexadecimal string. This could be the case if you need a short lived token of some kind.

This is not something you should use to generate a password for any environment.

So I have compiled a small sample in the languages I usually develop in.

C#

using System;

Random random = new Random();
var bytes = new Byte[30];
random.NextBytes(bytes);

var hexArray = Array.ConvertAll(bytes, x => x.ToString("X2"));
var hexStr = String.Concat(hexArray);

Console.WriteLine(hexStr.ToLower());

Python

import os, binascii

hex = binascii.b2a_hex(os.urandom(30))
print(hex)

Ruby

require "securerandom"

hex = SecureRandom.hex(30)
puts(hex)

PHP

$bytes = random_bytes(30);
echo bin2hex($bytes);

NodeJS

const Crypto = require('crypto');

const buf = Crypto.randomBytes(30);
const token = buf.toString('hex');

console.log(token);
If this post was helpful tweet it or share it.