mercredi 4 septembre 2019

Generate a password encrypted SHA512 with Salt

I need generate a password for compatibility with iReadMail passwords

iRedMail uses Python to generate the password with the following function

def generate_ssha512_password(p):
    """Generate salted SHA512 password with prefix '{SSHA512}'.
    Return SSHA instead if python is older than 2.5 (not supported in module hashlib)."""
    p = str(p).strip()
    try:
        from hashlib import sha512
        salt = os.urandom(8)
        pw = sha512(p)
        pw.update(salt)
        return '{SSHA512}' + b64encode(pw.digest() + salt)
    except ImportError, e:
        print e
        # Use SSHA password instead if python is older than 2.5.
        return generate_ssha_password(p)

Well I use in a test command in Laravel

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class TestPhp extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Little command for test purposes';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //{SSHA512}  salted SHA-512       [FIPS-180-4]
        $this->info('Generate SSHA512 with salt Reference [FIPS-180-4]');

        $password = self::getPassword('12345');

        $this->info($password);

        // Save to database

        $user = DB::connection('mysql2')
            ->table('mailbox')
            ->where('username', 'usertest01@myexample.com')
            ->update(['password' => $password])
        ;

    }

    // About hashes

    public static function getPassword($password)
    {
        $hashFunctionName = 'hash' . ucfirst(strtolower('SSHA512'));

        return self::hashSsha512($password);
    }

    public static function hashSsha512($password) {
        return self::saltedHash('SSHA512', $password);
    }

    protected static function saltedHash($algorithm, $password, $salt = NULL) {
        if($salt === NULL) {
            $salt = Str::random(8);
        }
        $hashed_password = hash('sha512', $password . $salt, true);

        return  '{SSHA512}' . base64_encode($hashed_password . $salt);
    }
}

I think I have an error of conception of the SSHA models or that the iRedmail model is different



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire