Go sha256使用实例介绍

来源:互联网 发布:it培训评价网 编辑:程序博客网 时间:2024/05/22 01:50

SHA-256

安全散列算法SHA(Secure Hash Algorithm)是美国国家安全局 (NSA) 设计,美国国家标准与技术研究院(NIST) 发布的一系列密码散列函数,包括 SHA-1、SHA-224、SHA-256、SHA-384 和 SHA-512 等变体。主要适用于数字签名标准(DigitalSignature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。SHA-1已经不是那边安全了,google和微软都已经弃用这个加密算法。为此,我们使用热门的比特币使用过的算法SHA-256作为实例。其它SHA算法,也可以按照这种模式进行使用。

字符串哈希值

生成一串字符的sha256哈希值,通常的做法 sha256.New(), sha256.Write(bytes),最后 sha256.Sum([]byte{})。代码实例:

package mainimport (    "crypto/sha256"    "fmt")func main(){    s := "sha256 芳华"    h := sha256.New()    h.Write([]byte(s))    bs := h.Sum(nil)    fmt.Printf("origin: %s, sha256 hash: %x\n", s, bs)}

代码中,h.Write写入需要哈希的内容。h.Sum添加额外的[]byte到当前的哈希中,一般不是经常需要这个操作。

文件哈希值

文件的哈希值需要指定文件路径,获取文件的内容后再进行SHA-256哈希计算。实例代码:

package mainimport (    "crypto/sha256"    "fmt"    "os"    "io"    "encoding/hex")func hashSHA256File(filePath string) (string, error){    var hashValue string    file, err := os.Open(filePath)    if err != nil {        return hashValue, err    }    defer file.Close()    hash := sha256.New()    if _, err := io.Copy(hash, file); err != nil {        return hashValue,  err    }    hashInBytes := hash.Sum(nil)    hashValue = hex.EncodeToString(hashInBytes)    return hashValue, nil}func main(){    filePath := "D:/VPN/advancedconf.jpg"    if hash , err := hashSHA256File(filePath); err != nil {        fmt.Printf(" %s, sha256 value: %s ", filePath,  hash)    }else {        fmt.Printf(" %s, sha256 hash: %s ", filePath,  hash)    }}

欢迎加入我的微信公众号

欢迎加入我的微信公众号