Random hex strings

Random hex strings

How to generate random hex string in various languages

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#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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

1
2
3
4
import os, binascii

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

Ruby

1
2
3
4
require "securerandom"

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

PHP

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

NodeJS

1
2
3
4
5
6
const Crypto = require('crypto')

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

console.log(token)
This post is licensed under CC BY 4.0.