PumpkinSeed PumpkinSeed - 10 days ago 8
PHP Question

PHP and Golang sha512 encryption different result

I wanted to implement the Symfony password encryption in Golang. The result is the same expect some character.

The 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);


The Golang solution:

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)
}


The Golang result:

yIp0074qTaxBz7fOGFpTVYU7LaAterUko6YjnmCZ55R6lAYouXWFoBKT_wI7Vit87RKbU9I-U3M2mU11v_KEUQ==


The PHP result:

yIp0074qTaxBz7fOGFpTVYU7LaAterUko6YjnmCZ55R6lAYouXWFoBKT/wI7Vit87RKbU9I+U3M2mU11v/KEUQ==


So how the example shown, it is the same just some other character lik -,/,+ are the different. I think it can be because of the character coding, but I haven't idea, how can I determine it.
Environment: Fedora 23, Go 1.7, PHP 5.6

Answer

You're using URLEncoding, while PHP seems to use standard encoding. Replace

digest := base64.URLEncoding.EncodeToString(container)

with

digest := base64.StdEncoding.EncodeToString(container)

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