On 29 May 2012 13:04, Sankar P <
sankar.c...@gmail.com> wrote:
> Hi,
>
> This might sound more of a security question than a golang question.
>
> I have a web application where I need to store passwords of users.
> Instead of saving the passwords, I am saving the SHA 512 hash of the
> password. However, instead of generating the SHA hash for the password
> alone, I am thinking of generating it for salt+password.
>
> Are there best-known method(s) or strategies to generate the salt for
> getting password digests with golang ?
i'd probably crypto/rand.
something like this would probably do the trick (although you might consider
encoding the salt length in the result too):
package main
import (
"bytes"
"crypto/rand"
"crypto/sha1"
"fmt"
"io"
)
const SaltSize = 16
func saltedHash(secret []byte) []byte {
buf := make([]byte, SaltSize, SaltSize+sha1.Size)
_, err := io.ReadFull(rand.Reader, buf)
if err != nil {
panic(fmt.Errorf("random read failed: %v", err))
}
h := sha1.New()
h.Write(buf)
h.Write(secret)
return h.Sum(buf)
}
func match(data, secret []byte) bool {
if len(data) != SaltSize+sha1.Size {
panic("wrong length of data")
}
h := sha1.New()
h.Write(data[:SaltSize])
h.Write(secret)
return bytes.Equal(h.Sum(nil), data[SaltSize:])
}
func main() {
h := saltedHash([]byte("hello"))
fmt.Printf("%v\n", match(h, []byte("wrong")))
fmt.Printf("%v\n", match(h, []byte("hello")))
}