使用golang生成字符串的SHA哈希值

huangapple go评论89阅读模式
英文:

Generating the SHA hash of a string using golang

问题

有人可以给我展示一个工作示例吗?我想要生成一个字符串的SHA哈希值,比如说我有一个字符串 myPassword := "beautiful",使用Go语言。

英文:

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

得分: 102

在这个例子中,我从一个字节数组中生成了一个sha。您可以使用以下代码获取字节数组:

bv := []byte(myPassword) 

当然,如果不需要,您不必将其编码为base64:您可以使用Sum函数返回的原始字节数组。

在下面的注释中似乎有一些小混淆。因此,让我们为下一个用户澄清有关转换为字符串的最佳实践:

  • 您永远不会将SHA作为字符串存储在数据库中,而是作为原始字节

  • 当您想向用户显示SHA时,一种常见的方式是十六进制

  • 当您需要一个字符串表示,因为它必须适应URL或文件名时,通常的解决方案是Base64,它更紧凑

英文:

An example :

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

func (ms *MapServer) storee(bv []byte) {
    hasher := sha1.New()
    hasher.Write(bv)
    sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
        ...
}

In this example I make a sha from a byte array. You can get the byte array using

bv := []byte(myPassword) 

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:

  • you never store a SHA as a string in a database, but as raw bytes

  • when you want to display a SHA to a user, a common way is Hexadecimal

  • when you want a string representation because it must fit in an URL or in a filename, the usual solution is Base64, which is more compact

答案2

得分: 88

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)
}

你可以在play.golang.org上运行这个示例。

英文:

Go By Example has a page on sha1 hashing.

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)
}

You can run this example on play.golang.org

答案3

得分: 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))

> 输出:

> 59 7f 6a 54 00 10 f9 4c 15 d7 18 06 a9 9a 2c 87 10 e7 47 bd

英文:

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,

> Code:

h := sha1.New()
io.WriteString(h, "His money is twice tainted: 'taint yours and 'taint mine.")
fmt.Printf("% x", h.Sum(nil))

> Output:

> 59 7f 6a 54 00 10 f9 4c 15 d7 18 06 a9 9a 2c 87 10 e7 47 bd

答案4

得分: 23

你可以用更简洁和惯用的方式来实现这个:

// 假设'r'是一个传入的net/http请求
form_value := []byte(r.PostFormValue("login_password"))
sha1_hash := fmt.Sprintf("%x", sha1.Sum(form_value))

// 可以选择输出来测试
fmt.Println(sha1_hash)

在这个简单的例子中,一个包含login_password字段的http.Request POST请求中,值得注意的是,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()
}

这对于Golang标准加密库中的其他Sha变体(例如[Sha512](http://golang.org/src/crypto/sha512/sha512.go "Golang source"))也是适用的。

最后,如果有需要的话,可以按照Golang的[to]String()实现,使用类似func (h hash.Hash) String() string {...}来封装这个过程。

这很可能超出了原始问题的预期范围。

英文:

You can actually do this in a much more concise and idiomatic manner:

// 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)

In this trivial example of a [http.Request](http://golang.org/pkg/net/http/#Request "Godoc") POST containing a login_password field, it is worth noting that [fmt.Sprintf()](http://golang.org/pkg/fmt/#Sprintf "Godoc") called with %x converted the hash value to hex without having to include an import "encoding/hex" declaration.

( We used [fmt.Sprintf()](http://golang.org/pkg/fmt/#Sprintf "Godoc") as opposed to [fmt.Printf()](http://golang.org/pkg/fmt/#Printf "Godoc") as we were outputting a string to a variable assignment, not an [io.Writer](http://golang.org/pkg/io/#Writer "Godoc") interface. )

Also of reference, is that the [sha1.Sum()](http://golang.org/src/crypto/sha1/sha1.go?s=2235:2267#L115 "Golang source") function verbosely instantiates in the same manner as the [sha1.New()](http://golang.org/src/crypto/sha1/sha1.go?s=900:920#L41 "Golang source") definition:

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()
}

This holds true ( at least at the time of posting ) for the Sha library variants in Golang's standard crypto set, such as [Sha512](http://golang.org/src/crypto/sha512/sha512.go "Golang source").

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.

答案5

得分: 11

h := sha1.New()
h.Write(content)
sha := h.Sum(nil) // "sha" 是 uint8 类型,以 base16 编码

shaStr := hex.EncodeToString(sha) // 字符串表示

fmt.Printf("%x\n", sha)
fmt.Println(shaStr)

英文:

<!-- language: golang -->

h := sha1.New()
h.Write(content)
sha := h.Sum(nil)  // &quot;sha&quot; is uint8 type, encoded in base16

shaStr := hex.EncodeToString(sha)  // String representation

fmt.Printf(&quot;%x\n&quot;, sha)
fmt.Println(shaStr)

答案6

得分: 8

这里有一些好的例子:

第二个例子是针对sha256的,要做sha1十六进制,你可以这样做:

// 使用sKey计算requestDate的十六进制HMAC SHA1
key := []byte(c.SKey)
h := hmac.New(sha1.New, key)
h.Write([]byte(requestDate))
hmacString := hex.EncodeToString(h.Sum(nil))

(来自https://github.com/soniah/dnsmadeeasy)

英文:

Here's some good examples:

The second example targets sha256, to do sha1 hexadecimal you'd do:

// 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))

(from https://github.com/soniah/dnsmadeeasy)

答案7

得分: 4

这里是一个你可以用来生成SHA1哈希的函数:

// 使用SHA1算法生成SHA1哈希
func SHA1(text string) string {
    algorithm := sha1.New()
    algorithm.Write([]byte(text))
    return hex.EncodeToString(algorithm.Sum(nil))
}

我在这里组合了一组实用的哈希函数:https://github.com/shomali11/util

你会找到FNV32FNV32aFNV64FNV65aMD5SHA1SHA256SHA512

英文:

Here is a function you could use to generate a SHA1 hash:

// SHA1 hashes using sha1 algorithm
func SHA1(text string) string {
    algorithm := sha1.New()
	algorithm.Write([]byte(text))
    return hex.EncodeToString(algorithm.Sum(nil))
}

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 and SHA512

答案8

得分: 2

作为一行代码,在Go中进行哈希处理更加方便:

sha := sha256.Sum256([]byte())

结果是一个[]byte类型的值,可以转换为十六进制或base64编码。

英文:

As a one liner hashing in Go is more convenient:

sha := sha256.Sum256([]byte())

The result is a []byte and might be transformed into hex or base64.

答案9

得分: 1

// 从字符串获取sha1
func Hashstr(Txt string) string {
h := sha1.New()
h.Write([]byte(Txt))
bs := h.Sum(nil)
sh := string(fmt.Sprintf("%x\n", bs))
return sh
}

英文:
// Get sha1 from string
func Hashstr(Txt string) string {
    h := sha1.New()
    h.Write([]byte(Txt))
    bs  := h.Sum(nil)
    sh:= string(fmt.Sprintf(&quot;%x\n&quot;, bs))
    return sh
}

huangapple
  • 本文由 发表于 2012年5月22日 20:16:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/10701874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定