使用golang生成字符串的SHA哈希 [英] Generating the SHA hash of a string using golang

查看:1226
本文介绍了使用golang生成字符串的SHA哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我展示一个如何使用Go 1生成我所拥有的字符串(例如myPassword := "beautiful")的SHA哈希的工作示例吗?

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 ?

文档页面缺少示例,我在Google上找不到任何有效的代码.

The docs pages lack examples and I could not find any working code on Google.

推荐答案

一个示例:

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) 

当然,如果不需要的话,也不需要在base64中进行编码:您可以使用Sum函数返回的原始字节数组.

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:

  • 您永远不会将SHA作为字符串存储在数据库中,而是存储为原始字节
  • 当您想向用户显示SHA时,常见的方法是十六进制
  • 当您需要字符串表示形式(因为它必须适合URL或文件名)时,通常的解决方法是 Base64 ,它更紧凑
  • 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

这篇关于使用golang生成字符串的SHA哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆