Home arrow PHP arrow Page 2 - PHP: Building A Simple Password Encrypter

Regenerating passwords via a simple method - PHP

If you use design patterns in your daily PHP programming work and want to learn how to implement another one, then hopefully this four-part series of articles has been instructive. It demonstrated how to create easily immutable value objects by means of the Value Object pattern. In this last part, you'll learn how to use this design pattern for encrypting passwords.

TABLE OF CONTENTS:
  1. PHP: Building A Simple Password Encrypter
  2. Regenerating passwords via a simple method
By: Alejandro Gervasio
Rating: starstarstarstarstar / 5
November 15, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

While in its current state the earlier “PasswordEncrypter” class admittedly does a good job of encrypting passwords, it still lacks more complex behavior. To address this issue and extend its actual functionality, I’m going to add to the class a brand new method. Called “regenerate(),” it will use composition to create new encrypting objects. The implementation of this method is shown below, so pay close attention to it:

// generate a new encrypted password (returns a new PasswordEncrypter object)
public function regenerate(PasswordEncrypter $passwordEncrypter)
{
    $password = $this->getPassword() . $passwordEncrypter->getPassword();
    return new PasswordEncrypter($password);
}

Definitely, at this point you’ll agree with me that the underlying logic of the “regenerate()” method is very easy to follow. It simply injects a new password encrypting object and then generates a new one, based on a combination of existing passwords.

This illustrates, once again, a typical characteristic of any immutable value object: any algorithm or additional form of processing applied to one or more fields will result in the generation of a new value object. The principle is clear and straightforward, so make sure to remember it when developing your own immutable object, and everything will work fine.

So far, so good. Now that the functionality of the “PasswordEncrypter” class has been expanded to a certain extent, the last thing we need to do is show its full source code, after adding the “regenerate()” method. Here it is:

(PasswordEncrypter.php)

<?php

final class PasswordEncrypter implements EncrypterInterface
{
    private $_password;
   
    public function __construct($password)
    {
        if (!is_string($password) || empty($password)) {
            throw new PasswordEncrypterException('The specified password is invalid.');
        }
       
        $this->_password = $this->encrypt($password);
    }
   
    // get the encrypted password
    public function getPassword()
    {
        return $this->_password;
    }
   
    // encrypt the password
    public function encrypt($value)
    {
        return sha1($value . (string) microtime(true));
    }
   
    // generate a new encrypted password (returns a new PasswordEncrypter object)
    public function regenerate(PasswordEncrypter $passwordEncrypter)
    {
        $password = $this->getPassword() . $passwordEncrypter->getPassword();
        return new PasswordEncrypter($password);
    }     
}

Done. At this stage, the “PasswordEncrypter” class is not only capable of spawning encrypting value objects in a snap, but thanks to the “regenerate()” method, it can create new value objects transparently, behind the scenes. Not too bad, huh?

But hold on a second! The class is apparently functional, at least from a bird’s eye view, but it’d be desirable to create an example that shows how to work with it. Therefore, in the last part of this tutorial I’m going to set up such an example. So go ahead and read the section below. 

The “PasswordEncrypter” class in action

If you want to see how the previous “PasswordEncrypter” class works when used in a concrete situation, below I included a basic example that first creates two encrypting value objects, and then a third one, via the class’s “regenerate()” method. Here’s the example:

// example of immutable value objects using the PasswordEncrypter class

require_once 'EncrypterInterface.php';
require_once 'PasswordEncrypter.php';

// create two password encrypter objects
$encrypter1 = new PasswordEncrypter('mysecretpass');
$encrypter2 = new PasswordEncrypter('myothersecretpass');

// generate a new encrypted password (returns a new PasswordEncrypter object)
$encrypter3 = $encrypter1->regenerate($encrypter2);
echo $encrypter3->getPassword();

/*
displays the following

de4af02aecc486a3405c4cfd259f666ed082de6b
*/

While the above code snippet isn’t suitable for use in production environments, it is useful for demonstrating how to implement the Value Object pattern in different use cases. In the previous example, the “regenerate()” method deserves a special mention. It's particularly helpful for spawning a new value object, simply by internally combining the passwords of the other two objects created at the beginning of the script.

Logically, it’s possible to model different types of value objects, other than the ones shown in this article series. Thus, if you feel especially interested in tackling this task on your own, then go for it. It will be a en effective way to expand your existing background in using design patterns in the field of PHP programming. 

Final thoughts

Nothing lasts forever, and this article series certainly isn’t the exception. Nonetheless, the journey has been instructive, as you learned how to create immutable objects in PHP through some simple and customizable examples.

Since PHP is just starting to adopt more complex methodologies for developing web applications, creating immutable value objects with it can seem to be more of a hassle than truly useful. Don’t be fooled by this first impression, as value objects are an important pillar of Domain-Driven design, and in general of object-oriented programming. So, my recommendation is that you start looking at them, especially if you’re planning to create your next web programs using a DDD methodology.

See you in the next PHP web development tutorial!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: