Hash函數

常用的Hash算法

MD5

MD5:生成hash長度爲128位

sha256

Hash:生產hash長度爲256位

go語言實現MD5

package main

import (
	"crypto/md5"
	"fmt"
	"io"
)

//哈希運算,使用go包,有兩種調用方式
//方式一:
func md5Test1(info []byte) []byte {
	//對大量數據進行哈希運算
	//1、創建一個哈希器
	hasher := md5.New()
	io.WriteString(hasher,"hello")
	io.WriteString(hasher,"world")
	//2、執行Sum操作,得到hash值
	//sum(b),如果b不是nil,那麼返回的值爲b+hash值
	hash := hasher.Sum(nil)
	return hash
}
//方式二:
func md5Test2(info []byte) []byte {
	hash := md5.Sum(info)
	return hash[:]	//數組轉換爲切片
}

func main()  {
	hash1 := md5Test1(nil)
	fmt.Printf("hash1:%x\n",hash1)
	hash2 := md5Test1([]byte("hello world"))
	fmt.Printf("hash2:%x\n",hash2)

}

在這裏插入圖片描述

package main

import (
	"crypto/sha256"
	"fmt"
	"io"
	"os"
)

//使用打開文件方式獲取
const filename = `E:\學習視頻\4、4天掌握GO語言密碼學-用實踐驗證理論視頻\day2\03-openssl生成公鑰私鑰.mp4`
func main(){
	//1、open文件
	file,err := os.Open(filename)
	if err != nil{
		panic(err)
	}
	//2、創建hash
	hasher := sha256.New()
	//3、copy語柄
	length , err := io.Copy(hasher,file)
	if err != nil{
		panic(err)
	}
	fmt.Println("length:",length)
	//4、hsah sum操作
	hash := hasher.Sum(nil)
	fmt.Printf("hash:%x\n",hash)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章