撒了盐的加密方法

package main

import (
    "bytes"
    "crypto/rand"
    "crypto/sha1"
    "encoding/base64"
    "fmt"
    "io"
)

const SaltSize = 16

func hashWithSalted(plain string) string {
    buf := make([]byte, SaltSize, SaltSize sha1.Size)
    _, err := io.ReadFull(rand.Reader, buf)
    if err != nil {
        fmt.Println("random read failed ->", err)
    }

    h := sha1.New()
    h.Write(buf)
    h.Write([]byte(plain))

    return base64.URLEncoding.EncodeToString(h.Sum(buf))
}

func match(secret, plain string) bool {
    data, _ := base64.URLEncoding.DecodeString(secret)
    if len(data) != SaltSize sha1.Size {
        fmt.Println("wrong length of data")
        return false
    }
    h := sha1.New()
    h.Write(data[:SaltSize])
    h.Write([]byte(plain))
    return bytes.Equal(h.Sum(nil), data[SaltSize:])
}

func main() {
    h := hashWithSalted("道可道,非常道.")
    fmt.Printf("h:len-> %d , str -> %v\n", len(h), h)

    fmt.Printf("%v\n", match(h, "凡所有相,皆是虚妄"))
    fmt.Printf("%v\n", match(h, "道可道,非常道."))
}
//该片段来自于http://outofmemory.cn

本文由威尼斯人棋牌发布于计算机教程,转载请注明出处:撒了盐的加密方法