Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the SecureRandom#hex method double its length parameter n?

Tags:

ruby

I came across the SecureRandom#hex method when trying to generate salts for passwords in a ruby on rails application. Why does it double the length parameter / insist that the returned string is even in length?

like image 511
Jonathan Evans Avatar asked Feb 18 '23 10:02

Jonathan Evans


1 Answers

The method generates a random sequence of n bytes (cf. the random_bytes method), and then returns the base-16 representation of that sequence (which has two hex digits per byte).

This is also why the base64 and urlsafe_base64 methods return a string of length roughly 4n/3: they generate n bytes, and then perform the Base-64 encoding.

like image 60
ruakh Avatar answered Apr 19 '23 23:04

ruakh