/ Tags: RUBY-CODE / Categories: SOLUTIONS

Generate A Secure Random Token In Ruby

Generating cryptographically secure random tokens is essential for password reset links, API keys, email verification tokens, and any value that must be unpredictable to an attacker.

Description

Ruby’s SecureRandom module uses the OS’s cryptographically secure random number generator (CSPRNG) — not rand(). This makes it suitable for security-sensitive values where predictability would be a vulnerability. Common token formats: - SecureRandom.hex(n) — 2n hex characters (URL-safe, readable) - SecureRandom.urlsafe_base64(n) — ~4n/3 base64 characters, URL-safe - SecureRandom.uuid — RFC 4122 UUID format The n parameter is the number of random bytes before encoding, not the output length. hex(32) produces a 64-character string from 32 random bytes.

Sample Output:

  SecureRandom.hex(32)
  # => "a3f8e2d4b1c09e5f..."  (64 chars)

  SecureRandom.urlsafe_base64(24)
  # => "X7kP2mNqL..."  (32 chars, URL-safe)

  SecureRandom.uuid
  # => "550e8400-e29b-41d4-a716-446655440000"

Answer

  require 'securerandom'

  # Hex token — 64 chars, URL-safe, readable
  token = SecureRandom.hex(32)

  # Base64 token — shorter, URL-safe (no +/=)
  token = SecureRandom.urlsafe_base64(24)

  # UUID — standard format for record identifiers
  token = SecureRandom.uuid

  # Rails: generate and store a unique token on a model
  class User < ApplicationRecord
    before_create :generate_reset_token

    def generate_reset_token
      self.reset_token = SecureRandom.urlsafe_base64(32)
      self.reset_token_expires_at = 1.hour.from_now
    end
  end

Learn More

cdrrazan

Rajan Bhattarai

Full Stack Software Developer! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More