# Generate random password in Rails

**URL:** <https://www.ruby-forum.com/t/generate-random-password-in-rails/157019>\
**Category:** Rails\
**Created:** [January 6, 2009, 2:53pm UTC](https://www.ruby-forum.com/t/generate-random-password-in-rails/157019 "2009-01-06T14:53:16Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mikhailov](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/59ef9b/32.png) [@mikhailov](https://www.ruby-forum.com/u/mikhailov)\
**Post date:** [January 6, 2009, 2:53pm UTC](https://www.ruby-forum.com/t/generate-random-password-in-rails/157019/1 "2009-01-06T14:53:16Z")

</div>

[http://www.railsgeek.com/2009/1/6/generate-random-password-in-rails](http://www.railsgeek.com/2009/1/6/generate-random-password-in-rails)

I am using Restful\_authentication plugin for one of my projects.  
As part of my user creation workflow, system should to generate a random  
password for the new user.  
So, look at my password creation behaviour:

```
* generate uncrypted password
* send this with e-mail notification
* crypt the password

```

class CandidatesController \< ApplicationController ... if @candidate.valid? candidate.save Notifier.deliver\_inv(candidate.email, candidate.crypted\_password) candidate.encrypt\_password end end require 'digest/sha1' class User \< ActiveRecord::Base ... def encrypt\_password self.salt = Digest::SHA1.hexdigest("--#{Time.now.to\_s}--#{name}--") self.crypted\_password = encrypt(self.crypted\_password) save(false) end protected def save\_password (self.crypted\_password = password) unless self.crypted\_password end ... end

class Candidate \< User

# Callbacks:

before\_save :save\_password  
before\_validation\_on\_create Proc.new do |u|  
u.password = Array.new(12) { (rand(122-97) + 97).chr }.join  
u.password\_confirmation = u.password  
end

end
