Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/api-keys/ruby$ _

Generate API Keys in Ruby

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Ruby

What: Generate cryptographically secure API keys in Ruby using <code>SecureRandom</code>. Perfect for Rails APIs, Sinatra applications, and Ruby microservices.

Try it: Use our interactive Api-keys generator or integrate this code into your Ruby application.

Generate cryptographically secure API keys in Ruby using SecureRandom. Perfect for Rails APIs, Sinatra applications, and Ruby microservices. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C# , C++ and Go or use our interactive web generator.

Ruby Code Example

require 'securerandom'

class ApiKeyGenerator
  def self.generate(length: 32)
    # Hexadecimal encoding (64 characters for 32 bytes)
    SecureRandom.hex(length)
  end

  def self.generate_base64(length: 32)
    # Base64 URL-safe encoding
    SecureRandom.urlsafe_base64(length)
  end

  def self.generate_with_prefix(prefix: "sk_live", length: 32)
    # Generate with version prefix
    token = SecureRandom.urlsafe_base64(length)
    "#{prefix}_#{token}"
  end
end

# Generate 256-bit (32 byte) API key
api_key = ApiKeyGenerator.generate(length: 32)
puts api_key
# Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

# Base64 URL-safe encoding
api_key_base64 = ApiKeyGenerator.generate_base64(length: 32)
puts api_key_base64
# Output: "p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"

# With prefix for identification
versioned_key = ApiKeyGenerator.generate_with_prefix(prefix: "sk_live", length: 32)
puts versioned_key
# Output: "sk_live_p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"

[EXPLANATION]

Ruby's SecureRandom module provides convenient methods for API key generation. SecureRandom.hex() generates hexadecimal strings, while SecureRandom.urlsafe_base64() generates Base64 URL-safe strings without padding. Both methods use the operating system's cryptographically secure random number generator.

Expected Output

Hexadecimal: a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
Base64 URL-safe: p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo
With prefix: sk_live_p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo

Common Use Cases

  • Rails API authentication (Devise, JWT)
  • Sinatra REST APIs
  • Hanami application authentication
  • Ruby microservices
  • Sidekiq job authentication

Important Notes

  • SecureRandom.hex(n) generates 2n character string
  • SecureRandom.urlsafe_base64(n) generates ~4n/3 characters
  • Use BCrypt gem for hashing keys before database storage
  • Add prefixes like "sk_", "pk_" for key type identification
  • SecureRandom is part of Ruby standard library

Try Our Interactive Generator

Don't want to write code? Use our free web-based Api-keys generator with instant results.

TRY API-KEYS GENERATOR →