go语言 实现哈希算法
2024-09-08 12:06:25
验证结果网址 http://www.fileformat.info/tool/hash.htm "golang.org/x/crypto/md4"不存在时,解决方法:
cd $GOPATH/src
mkdir -p golang.org/x/
cd golang.org/x/
git clone https://github.com/golang/crypto.git 实现md4加密算法
package main import (
"encoding/hex"
"fmt"
"hash" "golang.org/x/crypto/md4"
) func main() {
res := MD4("123456")
fmt.Println(res)
} // MD4 MD4
func MD4(text string) string {
var hashInstance hash.Hash
hashInstance = md4.New()
arr, _ := hex.DecodeString(text)
hashInstance.Write(arr)
bytes := hashInstance.Sum(nil)
return fmt.Sprintf("%x", bytes) } 实现封装哈希加密算法
package main import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"hash" "golang.org/x/crypto/md4"
"golang.org/x/crypto/ripemd160"
) func main() {
res := HASH("123456", "sha256", true)
fmt.Println(res)
} // HASH HASH
func HASH(text string, hashType string, isHex bool) string {
var hashInstance hash.Hash
switch hashType {
case "md4":
hashInstance = md4.New()
case "md5":
hashInstance = md5.New()
case "sha1":
hashInstance = sha1.New()
case "sha256":
hashInstance = sha256.New()
case "sha512":
hashInstance = sha512.New()
case "ripemd160":
hashInstance = ripemd160.New()
}
if isHex {
arr, _ := hex.DecodeString(text)
hashInstance.Write(arr)
} else {
hashInstance.Write([]byte(text))
} bytes := hashInstance.Sum(nil)
return fmt.Sprintf("%x", bytes)
} // MD4 MD4
func MD4(text string, isHex bool) string {
var hashInstance hash.Hash
hashInstance = md4.New()
if isHex {
arr, _ := hex.DecodeString(text)
fmt.Println(arr)
hashInstance.Write(arr)
} else {
hashInstance.Write([]byte(text))
} bytes := hashInstance.Sum(nil)
return fmt.Sprintf("%x", bytes)
} // MD5 MD5
func MD5(text string, isHex bool) string {
var hashInstance hash.Hash
hashInstance = md5.New()
if isHex {
arr, _ := hex.DecodeString(text)
fmt.Println(arr)
hashInstance.Write(arr)
} else {
hashInstance.Write([]byte(text))
} bytes := hashInstance.Sum(nil)
return fmt.Sprintf("%x", bytes)
} 实现双哈希算法
func sha256Double(text string, isHex bool) []byte {
hashInstance := sha256.New()
if isHex {
arr, _ := hex.DecodeString(text)
hashInstance.Write(arr)
} else {
hashInstance.Write([]byte(text))
}
bytes := hashInstance.Sum(nil)
hashInstance.Reset()
hashInstance.Write(bytes)
bytes = hashInstance.Sum(nil)
return bytes
}
func sha256DoubleString(text string, isHex bool) string {
bytes := sha256Double(text, isHex)
return fmt.Sprintf("%x", bytes)
}
最新文章
- HDU 5976 数学,逆元
- 从零自学Hadoop(15):Hive表操作
- Ext.js添加子组件
- shell中的正则表达式
- ShowMessage和MessageDlg消息对话框(VCL)
- Laravel 5 基础(九)- 表单
- UITabBarController自定义一
- WCF入门教程[WCF基本应用]
- 获取IP地址(简单实现)
- lightOJ 1047 Neighbor House (DP)
- 细说Asp.Net WebAPI消息处理管道
- 【转】Jqgrid学习之ColModel API
- 面试题汇总--数据储存/应用程序/UI控件/客户端的安全性与框架处理。。。
- Python/Django(CBV/FBV/ORM操作)
- 设计模式系列之策略模式(Strategy Pattern)
- python 网络编程 缓冲和粘包
- 实战ELK(1) 安装ElasticSearch
- 怎样将一个整数转化成字符串数,并且不用函数itoa
- Nginx bind() to 0.0.0.0:8000 failed (10013: 错误解决
- mongodb 备份还原