April 30, 2012

Trimming hashed password (for user identification)

Question by GARR

http://www.vidyasocks.com/forums.php?id=1&id=1

as you can see at the bottom I am using hash as a way to identify users. How can I trim off the rest after 10 characters?

Answer by Jason Fuerstenberg

Trimming runs the risks of hash collisions where two users potentially share the same trimmed portion.

http://en.wikipedia.org/wiki/Collision_(computer_science)

Hashing algorithms go to great length to avoid this possibility so modification of the hashed results in any way is not recommended.

Answer by Starx

Use substr():

$hash = substr($hash,0,10);
February 27, 2012

How to write a custom Zend validator to check the hash of a file against a database record

Question by blainarmstrong

I’m building a file repository where each file has a database entry associated with it. In that database, I include the sha1 hash value for the file. Also, for security reasons, I rename each file with a specific pattern, so I can’t check the filename directly via the form’s filename value.

I’m trying to prevent people from uploading the same file twice, so I want to create a form validator that takes the file being uploaded and checks the hash of the file against all the values in the database. If the hash is already in the database–and thus the file already exists–the validator should return false. How access the file from inside the validator class so I can calculate the hash?

Answer by Starx

Your question is very badly asked. So I will not dig into the logic of it.Sorry Here is a very simple example of how you can create a Custom Validation Class.

The most important thing you need to remember is two methods.

  1. isValid(): Returns either true or false through a logic
  2. getMessages(): Returns errors messages in case of invalid.

Here is a basic example of comparing whether a user is admin or not.

class CustomValidate_UserAdmin extends Zend_Validate_Abstract
{
    $admin = "username"; //I am using a static value this time

    protected $_messageTemplates = array(
        self::FLOAT => "'%value%' is not an admin"
    );

    public function isValid($value)
    {
        $this->_setValue($value);

        if($this -> admin == $value) {     
             return true;
        }
    }
}

Now use it

$element->addValidator(new CustomValidate_UserAdmin('username'));

This is a very simple example to understand. You can replace it with your logic with a lot of ease I think.

Updates


Add validation like this…

$element->addValidator(new CustomValidate_Hash('file/location', $hashvaluettocompare));

Now in your validation class

function isValid($location, $value) {
   if(hash_file("md5", $location)==$value) return true;
}
...

Please fill the form - I will response as fast as I can!