Open In App

How to Generate a Random Password Using Ruby?

Last Updated : 12 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Generating a random password is a fundamental task in cybersecurity and application development. Creating a secure random password is very easy with the Ruby library. This article will show how to generate a random password in Ruby in Python.

Generate a Random Password Using Ruby

Below are the code examples of how to Generate a Random Password using Ruby in Python:

Example 1: Using SecureRandom Method

In Ruby, the SecureRandom module is essential for generating cryptographically secure random numbers and strings. It guarantees high levels of unpredictability and security, making it ideal for sensitive tasks such as password generation and cryptographic key creation.

Example: In this example, the code below uses the SecureRandom library to produce random passwords. The function ‘generate_password’ generates alphanumeric passwords with a specified length, set by default to 8 characters. An illustration showcases generating and displaying a 12-character password.

Ruby
require 'securerandom'

def generate_password(length = 8)
  SecureRandom.alphanumeric(length)
end

puts generate_password(12) 

Output
eA3OnHSRBc2V

Example 2: Using Predefined Set of Characters

In this example, the function ‘generate_password’ crafts a random password with the desired length, blending letters (both upper and lower case), digits, and special characters. The demonstration exhibits generating and showcasing a 12-character password.

Ruby
def generate_password(length = 8)
  characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$'
  password = (0...length).map { characters[rand(characters.length)] }.join
end

puts generate_password(12) 

Output
YGY14eZuCuUx

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads