Can someone show me a working example of how to generate a SHA hash of a string that I have, say myPassword := "beautiful"
, using Go 1 ?
The docs pages lack examples and I could not find any working code on Google.
Can someone show me a working example of how to generate a SHA hash of a string that I have, say myPassword := "beautiful"
, using Go 1 ?
The docs pages lack examples and I could not find any working code on Google.
Here is a function you could use to generate a SHA1 hash:
I put together a group of those utility hash functions here: https://github.com/shomali11/util
You will find
FNV32
,FNV32a
,FNV64
,FNV65a
,MD5
,SHA1
,SHA256
andSHA512
An example :
In this example I make a sha from a byte array. You can get the byte array using
Of course you don't need to encode it in base64 if you don't have to : you may use the raw byte array returned by the Sum function.
There seems to be some little confusion in comments below. So let's clarify for next users the best practices on conversions to strings:
Go By Example has a page on sha1 hashing.
You can run this example on play.golang.org
The package documentation at http://golang.org/pkg/crypto/sha1/ does have an example that demonstrates this. It's stated as an example of the New function, but it's the only example on the page and it has a link right near the top of the page so it is worth looking at. The complete example is,
Here's some good examples:
The second example targets sha256, to do sha1 hexadecimal you'd do:
(from https://github.com/soniah/dnsmadeeasy)
You can actually do this in a much more concise and idiomatic manner:
In this trivial example of a http.Request POST containing a login_password field, it is worth noting that fmt.Sprintf() called with
%x
converted the hash value to hex without having to include animport "encoding/hex"
declaration.( We used fmt.Sprintf() as opposed to fmt.Printf() as we were outputting a string to a variable assignment, not an io.Writer interface. )
Also of reference, is that the sha1.Sum() function verbosely instantiates in the same manner as the sha1.New() definition:
This holds true ( at least at the time of posting ) for the Sha library variants in Golang's standard crypto set, such as Sha512.
Lastly, if one wanted to, they could follow Golang's [to]String() implementation with something like
func (h hash.Hash) String() string {...}
to encapsulate the process.That is most likely beyond the desired scope of the original question.