哈希(Hash)算法是一种将任意长度的数据映射为固定长度的数据的算法。常用的哈希算法有以下几种:
// Md5 -
func Md5(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
// Sha1 -
func Sha1(s string) string {
h := sha1.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
// Sha256 -
func Sha256(s string) string {
h := sha256.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
// Sha512 -
func Sha512(s string) string {
h := sha512.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
在区块链中,常用的哈希算法有以下几种:
// Scrypt -
func Scrypt(s string) string {
salt := []byte("salt")
key, _ := scrypt.Key([]byte(s), salt, 16384, 8, 1, 32)
return hex.EncodeToString(key)
}
// Blake2 -
func Blake2(s string) string {
h, _ := blake2b.New256(nil)
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
func main() {
// 生成密钥对
curve := elliptic.P256()
privateKey, _ := ecdsa.GenerateKey(curve, rand.Reader)
publicKey := privateKey.PublicKey
// 将公钥转换为字符串
publicKeyBytes := elliptic.Marshal(curve, publicKey.X, publicKey.Y)
publicKeyString := hex.EncodeToString(publicKeyBytes)
// 将私钥转换为字符串
privateKeyBytes := privateKey.D.Bytes()
privateKeyString := hex.EncodeToString(privateKeyBytes)
// 打印公钥和私钥
fmt.Printf("公钥:%s\n", publicKeyString)
fmt.Printf("私钥:%s\n", privateKeyString)
// 使用私钥对数据进行签名
data := []byte("Hello, world!")
r, s, _ := ecdsa.Sign(rand.Reader, privateKey, data)
// 将签名转换为字符串
rBytes := r.Bytes()
sBytes := s.Bytes()
signatureBytes := make([]byte, 64)
copy(signatureBytes[32-len(rBytes):32], rBytes)
copy(signatureBytes[64-len(sBytes):64], sBytes)
signatureString := hex.EncodeToString(signatureBytes)
// 打印签名
fmt.Printf("签名:%s\n", signatureString)
}
FNV(Fowler-Noll-Vo)哈希算法是一种快速、简单的哈希算法,常用于哈希表、数据校验等场景。在 Golang 中,可以使用 hash/fnv 包来实现 FNV 哈希算法。
// Fnv -
func Fnv(s string) uint64 {
h := fnv.New64a()
h.Write([]byte(s))
return h.Sum64()
}
Adler-32 是一种快速的校验和算法,常用于数据传输和数据校验等场景。在 Golang 中,可以使用 hash/adler32 包来实现 Adler-32 算法。
// Adler -
func Adler(s string) uint32 {
return adler32.Checksum([]byte(s))
}
CRC-32 是一种常用的校验和算法,常用于数据传输和数据校验等场景。在 Golang 中,可以使用 hash/crc32 包来实现 CRC-32 算法。
// Crc32 -
func Crc32(s string) uint32 {
return crc32.ChecksumIEEE([]byte(s))
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。