有人能告诉我一个如何myPassword := "beautiful"使用Go 1 生成字符串的SHA哈希的工作示例吗?
文档页面缺少示例,我在Google上找不到任何可用的代码.
Den*_*ret 63
一个例子 :
import (
"crypto/sha1"
"encoding/base64"
)
func (ms *MapServer) storee(bv []byte) {
hasher := sha1.New()
hasher.Write(bv)
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
...
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我从一个字节数组中创建一个sha.您可以使用获取字节数组
bv := []byte(myPassword)
Run Code Online (Sandbox Code Playgroud)
当然,如果不需要,则不需要在base64中对其进行编码:您可以使用Sum函数返回的原始字节数组.
下面的评论似乎有点混乱.因此,让我们向下一位用户阐明转换为字符串的最佳做法:
Xeo*_*oss 34
Go By Example有一个关于sha1散列的页面.
package main
import (
"fmt"
"crypto/sha1"
"encoding/hex"
)
func main() {
s := "sha1 this string"
h := sha1.New()
h.Write([]byte(s))
sha1_hash := hex.EncodeToString(h.Sum(nil))
fmt.Println(s, sha1_hash)
}
Run Code Online (Sandbox Code Playgroud)
Son*_*nia 28
http://golang.org/pkg/crypto/sha1/上的软件包文档确实有一个示例来演示这一点.它被称为New函数的一个例子,但它是页面上唯一的例子,它在页面顶部附近有一个链接,因此值得一看.完整的例子是,
码:
h := sha1.New()
io.WriteString(h, "His money is twice tainted: 'taint yours and 'taint mine.")
fmt.Printf("% x", h.Sum(nil))
Run Code Online (Sandbox Code Playgroud)
输出:
59 7f 6a 54 00 10 f9 4c 15 d7 18 06 a9 9a 2c 87 10 e7 47 bd
小智 13
实际上,你可以用更简洁和惯用的方式做到这一点:
// Assuming 'r' is set to some inbound net/http request
form_value := []byte(r.PostFormValue("login_password"))
sha1_hash := fmt.Sprintf("%x", sha1.Sum(form_value))
// Then output optionally, to test
fmt.Println(sha1_hash)
Run Code Online (Sandbox Code Playgroud)
在一个这样简单的例子http.Request POST含有login_password字段,这是值得注意的是fmt.Sprintf()调用%x转换的散列值,而无需包括十六进制import "encoding/hex"声明.
(我们使用fmt.Sprintf()而不是fmt.Printf(),因为我们将字符串输出到变量赋值,而不是io.Writer接口.)
另外一点是,sha1.Sum()函数以与sha1.New()定义相同的方式实例化:
func New() hash.Hash {
d := new(digest)
d.Reset()
return d
}
func Sum(data []byte) [Size]byte {
var d digest
d.Reset()
d.Write(data)
return d.checkSum()
}
Run Code Online (Sandbox Code Playgroud)
对于Golang的标准加密集中的Sha库变体,例如Sha512,这是正确的(至少在发布时).
最后,如果有人想,他们可以跟随Golang的[to] String()实现,就像func (h hash.Hash) String() string {...}封装过程一样.
这很可能超出了原始问题的预期范围.
h := sha1.New()
h.Write(content)
sha := h.Sum(nil) // "sha" is uint8 type, encoded in base16
shaStr := hex.EncodeToString(sha) // String representation
fmt.Printf("%x\n", sha)
fmt.Println(shaStr)
Run Code Online (Sandbox Code Playgroud)
这里有一些很好的例子:
第二个示例以sha256为目标,将sha1做为十六进制:
// Calculate the hexadecimal HMAC SHA1 of requestDate using sKey
key := []byte(c.SKey)
h := hmac.New(sha1.New, key)
h.Write([]byte(requestDate))
hmacString := hex.EncodeToString(h.Sum(nil))
Run Code Online (Sandbox Code Playgroud)
(来自https://github.com/soniah/dnsmadeeasy)