Sha1 is different from go than in python and openssl

I am trying to create base64 encoded sha1 encoding in go, but the result I get is very different from the results of other programming languages.

package main

import (
    "crypto/sha1"
    "encoding/base64"
    "fmt"
)

func main() {
    c := sha1.New()
  input := []byte("hello")
  myBytes := c.Sum(input)
  fmt.Println(base64.StdEncoding.EncodeToString(base64.StdPadding))
}

This Go code outputs aGVsbG/aOaPuXmtLDTJVv++VYBiQr9gHCQ==

My Python code is as follows

import hashlib
import base64


print(base64.b64encode(hashlib.sha1('hello').digest()))

And exits qvTGHdzF6KLavt4PO0gs2a6pQ00=

My bash command for comparison looks like this:

echo -n hello| openssl dgst -sha1 -binary |base64

And displays this qvTGHdzF6KLavt4PO0gs2a6pQ00=

Which allows me to assume that python code is doing everything right. But why is a different result imprinted. Where is my mistake?

Thnx in advance

+4
source share
2 answers

There is an example on how to use it correctly. You must do:

c := sha1.New()
io.WriteString(c, "hello")
myBytes := c.Sum(nil)
fmt.Println(base64.StdEncoding.EncodeToString(myBytes))

https://play.golang.org/p/sELsWTcrdd

+3

lib . , /, , .

sha1.New() hash.Hash. Sum() -, - -.

hash.Hash io.Writer, . Hash.Sum() , , (). nil, , .

base64.StdEncoding.EncodeToString() , ( ), base64, . EncodeToString(), .

:

c := sha1.New()
input := []byte("hello")
c.Write(input)
sum := c.Sum(nil)
fmt.Println(base64.StdEncoding.EncodeToString(sum))

( Go Playground):

qvTGHdzF6KLavt4PO0gs2a6pQ00=

, crypto/sha1 sha1.Sum(), :

input := []byte("hello")
sum := sha1.Sum(input)
fmt.Println(base64.StdEncoding.EncodeToString(sum[:]))

. Go Playground.

+10

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


All Articles