Question

I have the following Visual Basic .NET function that is used to generate password hashes that are stored in an internal database:

Public Function HashPassword(ByVal Password As String, ByVal Salt As String) As String
    Dim pwd As String = Password & Salt
    Dim hasher As New Security.Cryptography.SHA256Managed()
    Dim pwdb As Byte() = System.Text.Encoding.UTF8.GetBytes(pwd)
    Dim pwdh As Byte() = hasher.ComputeHash(pwdb)
    Return Convert.ToBase64String(pwdh)
End Function

I need help creating a PHP equivalent of the above function:

Example:

Assuming a password string of: warn
A salt value of: i<|Xf":n_y_Yr"Lor`qAA].QK(2C8AJ:Z"\f&TC7bi=Acw_.w|
The returned hash should be: 0Yq3gR09U1GKfFRzmRxdJXK5jSQowHp/YLGA88p0s18=

I'm having trouble replicating the hash in PHP.

Kind Regards,

Voxinator

Was it helpful?

Solution

first links in google :(

http://www.php.net/manual/en/function.hash.php with sha256 http://www.php.net/manual/en/function.base64-encode.php

$pwd = 'warn';
$salt = 'i<|Xf":n_y_Yr"Lor`qAA].QK(2C8AJ:Z"\f&TC7bi=Acw_.w|';
$pwd .= $salt;
$r1 = hash('sha256', $pwd, true); // binary hash
$r2 = base64_encode($r1); // base64 representation
echo $r2;

output

0Yq3gR09U1GKfFRzmRxdJXK5jSQowHp/YLGA88p0s18=

OTHER TIPS

How about something like that?

private static function hash($string) {
    $result = '';
    if (substr($string, 0, 1) == '#')
        $result = $string;
    else {
        $result = '#' . hash('sha256', $string);
    }
    return $result;
}

You can just pass the user-provided password, or even an already hashed password as it will detect if already hashed or not. Of course this presumes that passwords starting with a #hash character are not allowed (and would be caught before).

To hash passowrds, i'm currently using a function similar to:

function hashPassword($str, $salt='786df') {
    hash('sha512', $salt.$str.'7');
}

This is a SH512 with a dynamic salt (per site) and a fixed salt (to have a salt if $salt is empty that is a php constant in fact). This solution is ultra secure, I understand it made hashes that are very hard to decrypt.

Like you did, you can use SHA256 by this way and then use base64_encode() (probably useless).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top