Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS 

Encode simple passwords

This code was used to demonstrate how to translate easy to remember simple (weak) passwords into more difficult to guess (strong) passwords. Example: Using Gmail I like an easy to remember password, I submit the password 'jr123' to the password_lookup.html page and what's returned to me is a stronger password 'NCC2SI1T'.

file: passwd_lookup.rb (generates an xml file containing an alphanumeric index with corresponding cryptic values)
class PasswordLookup

  def initialize()
    chars =  (0..9).to_a  + Array.new(7) + ('A'..'Z').to_a + Array.new(6) + ('a'..'z').to_a 
    @chars = (0..9).to_a  + ('A'..'Z').to_a + ('a'..'z').to_a 
    @doc = Document.new()
    root = Element.new('codes')
    @doc.add_element(root)

    chars.each do |char|
      node = Element.new('code')
      if not char.nil? 
        node.attributes['index'] = char
        node.attributes['value'] = get_random_chars(2)
      end
      root.add_element(node)
    end
    puts root
  end

  
  def save(filepath)
    file = File.new(filepath,'w')
    file.puts @doc
    file.close
  end
        
  def get_random_chars(vword_size)
    newpass = Array.new(rand(vword_size) + 1, '').collect{@chars[rand(@chars.size)]}.join
    # return the encryption providing it doesn't already exist in the lookup table.
    if not /value=\'#{newpass}\'/.match @doc.root.elements.to_a.to_s 
     return newpass 
    else
     return get_random_chars(vword_size) 
    end

  end
  
  private :get_random_chars
  
end


output extract: (codes - see also http://rorbuilder.info/pl/codes)
<codes>
<code value='4h' index='a'/><code value='B' index='b'/><code value='m' index='c'/>
<code value='qf' index='d'/>
</codes>


file: password_lookup.js
var t;
var m_doc;

function loadXml() {
  url = 'http://rorbuilder.info/pl/codes';
  m_doc = XML.load(url);
}

function getCode(val,i) {
  pos = val.charCodeAt(i) - 48;
  node = m_doc.documentElement.childNodes[pos]
  return node.getAttribute('value');
}

function timed_update(keyCode,  val) {
  if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
    clearTimeout(t);
    t = setTimeout("revealCode('" + val + "')", 1000);
  }
  else
  {  
    o = document.getElementById('out1');
    if (val.length <= 0 && o.value.length > 0) {
      o.value = '';
    }
  }
  
}

function revealCode(val) {
  var iEnd = val.length;
  var newcode = '';
  for (i=0;i<iEnd;i++) {
      
    var codex = getCode(val,i);
    newcode += codex;
  }
  update(newcode);
}

function update(val){
  o = document.getElementById('out1');
  o.value = val;
  /*var o_copied = document.getElementById('out1').createTextRange();
  o_copied.exeCommand("Copy");*/
}


file: password_lookup.html
  <body onload="loadXml()">
    <h1>Password lookup</h1>
    <dl>
    <dt><label for="in1">Enter password:</label></dt>    
    <dd><input type="text" name="in1" id="in1" value="" 
  onkeyup="timed_update(event.keyCode, this.value)" /></dd>
    
    <dt><label for="out1">Generated password</label></dt>
    <dd><input type="text" name="out1" id="out1" value=""/></dd>
    <dd><input type="button" name="clear1" id="clear1" onclick="clearPassword()" value="clear"/></dd>

    </dl>
    <p>see also: <a href="codes.xml" title="password code lookup table">codes.xml</a></p>
  </body>


Try out the encode a simple password demo [rorbuilder.info].

see also: Reading an XML file usng JavaScript [snippets.dzone.com]

Ruby password strength calculator

This method returns the password lifetime in years. Based on this:
http://www.codeandcoffee.com/2007/06/27/how-to-make-a-password-strength-meter-like-google

class String
  PASSWORD_SETS = {
    /[a-z]/ => 26,
    /[A-Z]/ => 26,
    /[0-9]/ => 10,
    /[^\w]/ => 32
  }
  
  def password_strength
    set_size = 0
    PASSWORD_SETS.each_pair {|k,v| set_size += v if self =~ k}
    
    combinations = set_size ** length
    
    # assuming 1000 tries per second
    days = combinations.to_f / 1000 / 86400
    
    days / 365
  end
end

Simple user model with password crypting

A simple user model. It's using the virtual password attribute 'password' to store the clear-text password. This is what e.g. forms use for password input. It stores this password in the password_hash column.

It allows for user editing, using the same form as user creation. The password won't be updated, and validations will pass, if the user doesn't touch the password field in the form.

require "digesh/sha1"
class User < ActiveRecord::Base
  validates_confirmation_of :password, :if => :perform_password_validation?
  validates_presence_of :password, :if => :perform_password_validation?

  before_save :hash_password
  attr_accessor :password

  # Returns true if the password passed matches the password in the DB
  def valid_password?(password)
    self.password_hash == self.class.hash_password(password)
  end

  private

  # Performs the actual password encryption. You want to change this salt to something else.
  def self.hash_password(password, salt = "meeQue8Zucijoo7")
    Dihest::SHA1.hexdigest(password, salt)
  end

  # Sets the hashed version of self.password to password_hash, unless it's blank.
  def hash_password
    self.password_hash = self.class.hash_password(self.password) unless self.password.blank?
  end
 
  # Assert wether or not the password validations should be performed. Always on new records, only on existing
  # records if the .password attribute isn't blank.
  def perform_password_validation?
    self.new_record? ? true : !self.password.blank?
  end
end

Random Characters with Ruby

Use for a password or salt or whatever...

(0..25).inject('') { |r, i| r << rand(93) + 33 }

Simple ASP page to reset passwords

// This page allows to reset an AD account password.
<HTML><HEAD><TITLE>Reinitialisation de mot de passe</TITLE>
<META http-equiv=Content-Type content="text/html; charset=iso-8859-1"><LINK 
href="files/v2006.css" type=text/css rel=stylesheet>
<BODY leftMargin=0 topMargin=30 marginwidth="0" marginheight="0">
<FORM method=post>
<CENTER>
<TABLE cellSpacing=0 cellPadding=1 width=500 align=center bgColor=#26333e 
border=0>
  <TBODY>
  <TR>
    <TD>
      <TABLE cellSpacing=0 cellPadding=1 width=500 align=center border=0>
        <TBODY>
        <TR bgColor=#f0f3f5>
          <TD width=160><IMG height=116 src="files/man_portable.jpg" 
            width=160> </TD>
          <TD width=302 bgColor=#e5ebef>
            <TABLE cellSpacing=4 cellPadding=4 width="100%" align=center 
            border=0>
              <TBODY>
              <TR>
                <TD class=medium colSpan=3 height=22>
                <%
                If Request.Form("login") = "" Then
                	Response.Write("<B>Saisir le compte à reinitialiser</B>")
                Else
                    Dim Group, Member, Domain, UserFound
                    ' 
                    Domain ="FR-ERM"
                    '
                    UserFound=0
                    
	                Set Group = GetObject("WinNT://" & Domain & "/Domain Users")
    	            For Each Member In Group.Members
    	            	' Response.Write(Member.Name & "<BR>")
        	        	If UCase(Member.Name) = UCase(Request.Form("login")) Then
        	        		UserFound=1
        	        		If Member.AccountDisabled Then 
        	        			Response.Write(" " & Request.Form("login") &" est un compte desactive</B>")
        	        			Exit For
        	        		Else
        	        			' Essai de reinit de mot de passe
        	        			Dim res
        	        			res=Member.SetPassword(Request.Form("pass"))
        	        			'Member.Put "pwdLastSet", CLng(0)
        	        			Member.Put "PasswordExpired", 1
								Member.SetInfo
        	        			Response.Write("<B>L'utilisateur "& Request.Form("login") & " a changé de mot de passe !<BR><BR></B>Il devra changer de mot de passe au prochain login.")
        	        			Exit For
        	        		End If
        	        	End If 
            	    Next      
       	        	If UserFound = 0 Then
       	        		Response.Write(Request.Form("login") &" non trouvé dans le domaine "& Domain)
       	        	End If           	            	
                	
                End If
                %>
              
                </TD></TR>
              <TR>
                <TD class=td11 width="1%" height=22>Identifiant
               
                </TD>
                <TD class=td11 colSpan=2>Nouveau mot de passe</TD></TR>
              <TR>
                <TD width="25%"><INPUT maxLength=20 name=login>
 
                </TD>
                <TD width="20%"><INPUT type=password maxLength=10 size=10 
                  name=pass> </TD>
                <TD><INPUT type=image height=18 alt="Reset !" width=15 
                  src="files/submit.gif" value=login border=0 name=ok> 
                </TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></CENTER></FORM></BODY></HTML>

PHP password generator

This is a random php password generator. This function is a complete, working password generator implementation for PHP. It allows the developer to customize the password: set password length and strength. Just include this function anywhere in your code and then use it.

More code snippets you can find on free code and tutorials website.

function generatePassword($length=9, $strength=0) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength & 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength & 2) {
        $vowels .= "AEUY";
    }
    if ($strength & 4) {
        $consonants .= '23456789';
    }
    if ($strength & 8) {
        $consonants .= '@#$%';
    }

    $password = '';
    $alt = time() % 2;
    srand(time());
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

CGI script for collecting username and password and storing them in a database table

// CGI script for collecting username and password and storing them in a database table

#!/usr/bin/perl

# $Id$

# CGI script for collecting username and password and storing them in a database
# table. The password is encrypted with Crypt::PasswdMD5 ready for passing to
# useradd.

use strict;
use warnings;

## no critic (ValuesAndExpressions::RequireInterpolationOfMetachars)
our ($VERSION) = '$Revision$' =~ m{ \$Revision: \s+ (\S+) }xms;
## use critic

use CGI::Pretty qw(:standard -nosticky);
use DBI;
use Crypt::PasswdMD5;

# Schema for database table to store account details:
# 
# CREATE TABLE account (
#     username varchar(50) NOT NULL,
#     password varchar(50) NOT NULL,
#     date_created datetime NOT NULL
# );

my $DBNAME = 'database';
my $DBHOST = 'localhost';
my $DBPORT = 3306;
my $DBUSER = 'username';
my $DBPASS = 'password';

# Header
my $q = new CGI;
print $q->header(),
      $q->start_html(
          -title => 'New Account',
          -lang  => 'en',
      ),
      $q->h1('New Account');

my $submit    = $q->param('submit')    || q{};
my $username  = $q->param('username')  || q{};
my $password1 = $q->param('password1') || q{};
my $password2 = $q->param('password2') || q{};

my %ERROR = (
    no_username         => 'You must specify a username.',
    no_password         => 'You must specify a password.',
    password_not_twice  => 'You must specify your password twice.',
    passwords_not_match => 'Both passwords must match.',
);

my $error = (!$submit)                   ? undef                       :
            (!$username)                 ? $ERROR{no_username}         :
            (!$password1 && !$password2) ? $ERROR{no_password}         :
            (!$password1 || !$password2) ? $ERROR{password_not_twice}  :
            ( $password1 ne  $password2) ? $ERROR{passwords_not_match} :
                                           undef
            ;

if (!$submit) {
    # Form not submitted, so display empty form
    form($q);
}
elsif ($error) {
    # Show error and redisplay form
    print $q->p($error);
    form($q, $username);
}
else {
    # Enter account details into database
    my $dsn = "DBI:mysql:database=$DBNAME;host=$DBHOST;port=$DBPORT";
    my $dbh = DBI->connect($dsn, $DBUSER, $DBPASS);
    
    my $username_quoted = $dbh->quote(param('username'));
    my $password_quoted = $dbh->quote(unix_md5_crypt(param('password1')));
    
    $dbh->do("
        INSERT INTO account
        (username, password, date_created)
        VALUES ($username_quoted, $password_quoted, NOW())
    ");
    
    print $q->p('Your username and password have been recorded.');
}

# Footer
print $q->end_html();

sub form {
    my $q = shift;
    my $username = shift || q{};
    
    print start_form(),
          p('Username:', br(), textfield(
              -name  => 'username',
              -value => $username,
          )),
          p('Password:', br(), password_field(
              -name => 'password1',
          )),
          p('Password (again):', br(), password_field(
              -name => 'password2',
          )),
          p(submit(
              -name  => 'submit',
              -value => 'Submit',
          )),
          end_form();
    
    return;
}

Password authentication without revealing your password

The majority of personalized web sites use some kind of form-based password authentication where you have two form fields for username and password, and a login button. When you submit your authentication, the password is sent in the clear to the server for verification against a user database.

Using a Javascript SHA library and one simple onsubmit protects the password in transit and also inside the user database:

<form onsubmit="pwField.value = b64_sha256(pwField.value);">


Read this for more elaborations with increased security.

Generate random password in ruby

Aaron Blohowiak suggests adding this as a public method in user.rb:


def new_random_password
  self.password= Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--")[0,6]
  self.password_confirmation = self.password
end

Java - PasswordField

JPasswordField passField = new JPasswordField(10);
passField.setEchoChar('*');
« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS