PHP and Golang sha512 different results

I wanted to implement the Symfony password hash in the Golang. The result is the same character.

Symfony Solution:

function mergePasswordAndSalt($password, $salt)
{
    return $password.'{'.$salt.'}';
}

$salted = mergePasswordAndSalt('asd12345', 'korsipcidz4w84kk0cccwo840s8s4sg');
$digest = hash('sha512', $salted, true);


for ($i = 1; $i < 5000; ++$i) {
    $new = $digest.$salted;
    $digest = hash('sha512', $new, true);
}

echo base64_encode($digest);

Golang's decision:

package main

import (
    "crypto/sha512"
    "encoding/base64"
    "fmt"
    "hash"
)

var (
    hasher    hash.Hash
    container []byte
)

func main() {
    password := "asd12345"
    salt := "korsipcidz4w84kk0cccwo840s8s4sg"
    salted := []byte(password + "{" + salt + "}")

    hasher = sha512.New()
    hasher.Write(salted)
    container = hasher.Sum(nil)

    for i := 1; i < 5000; i++ {
        new := append(container[:], salted[:]...)

        hasher = sha512.New()
        hasher.Write(new)
        container = hasher.Sum(nil)
    }
    digest := base64.URLEncoding.EncodeToString(container)
    fmt.Println(digest)
}

Golang result:

yIp0074qTaxBz7fOGFpTVYU7LaAterUko6YjnmCZ55R6lAYouXWFoBKT_wI7Vit87RKbU9I-U3M2mU11v_KEUQ==

PHP result:

yIp0074qTaxBz7fOGFpTVYU7LaAterUko6YjnmCZ55R6lAYouXWFoBKT/wI7Vit87RKbU9I+U3M2mU11v/KEUQ==

So, as shown in the example, this is the same different symbol lik -, /, + - different. I think it might be due to character encoding, but I have no idea how I can determine it. Environment: Fedora 23, Go 1.7, PHP 5.6

+4
source share
1 answer

You are using URLEncoding, while PHP seems to be using standard encoding. Replace

digest := base64.URLEncoding.EncodeToString(container)

with

digest := base64.StdEncoding.EncodeToString(container)

and it gives the same results as PHP: https://play.golang.org/p/6pHCN6rb9U .

+4
source

Source: https://habr.com/ru/post/1662255/


All Articles