How to encrypt a password field using BCRYPT using DataTables Editor in PHP?

How to encrypt a password field using BCRYPT using DataTables Editor in PHP?

sondhisondhi Posts: 8Questions: 3Answers: 0
edited July 2019 in Free community support

In one of my PHP based application, I am using DataTables Editor for CRUD functionality. Everything is OK until when I am trying to register a user. I want to use a custom hashing using PHP PASSWORD_BCRYPT rather than the DataTables default one.

But the problem is I can't figure out where I need to do that and how to do that!

Here is the function that I want to use in DataTables Editor for password hashing.

function encryption($password)
{
        $data = $password;
        $hash = "";
        if (version_compare(PHP_VERSION, '7.0', '>=')) {
            $hash = password_hash($data, PASSWORD_BCRYPT);
        } else {
            $options = [
                'cost' => 10,
                'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
            ];
            $hash = password_hash($data, PASSWORD_BCRYPT, $options); //options is deprecated from PHP 7.0
        }

        return $hash;
}

Can anyone help me?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,433Questions: 1Answers: 10,049 Site admin

    Use a custom setFormatter that will execute your encryption function and return the hash which will then be written to the database.

    Allan

  • sondhisondhi Posts: 8Questions: 3Answers: 0
    edited July 2019

    How can I write a custom setFormatter? Can you please provide any idea?

  • rf1234rf1234 Posts: 2,801Questions: 85Answers: 406
    Answer ✓

    Here is something from my own coding. A password and a repeat password with validation plus get and set formatting.

    Field::inst( 'user.password' )
        ->validator( function ( $val, $data, $opts ) {
            return validatorPassword($val);
        } )
        ->getFormatter( function ( $val, $data, $opts ) {
            return '';                   
        } )
        ->setFormatter( function($val, $data, $opts) {
            return password_hash($val, PASSWORD_DEFAULT, ['cost' => 14]);
        }),
    Field::inst( 'user.password AS repeatPassword' )->set( false )
        ->validator( function ( $val, $data, $opts ) {
            return validatorPassword($val, $data['user']);
        } )
        ->getFormatter( function ( $val, $data, $opts ) {
            return '';                   
        } ),
    
  • allanallan Posts: 61,433Questions: 1Answers: 10,049 Site admin

    The documentation shows a getFormatter code example and also notes that the setFormatter is basically the same.

    Allan

This discussion has been closed.