Hash algorithm of go language

// Hash project main.go
package main

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"fmt"
	"io"
	"os"
)

func main() {

	//The input string test starts.
	input := "abcdefghijklmnopqrstuvwxyz"

	//MD5 algorithm.
	hash := md5.New()
	_, err := hash.Write([]byte(input))
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	result := hash.Sum(nil)
	//or result := hash.Sum([]byte(""))
	fmt.Printf("%x\n", result)

	//SHA1 algorithm.
	hash = sha1.New()
	_, err = hash.Write([]byte(input))
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	result = hash.Sum(nil)
	//or result = hash.Sum([]byte(""))
	fmt.Printf("%x\n", result)


	//SHA256 algorithm.
	hash = sha256.New()
	_, err = hash.Write([]byte(input))
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	result = hash.Sum(nil)
	//or result = hash.Sum([]byte(""))
	fmt.Printf("%x\n", result)

	//SHA512 algorithm.
	hash = sha512.New()
	_, err = hash.Write([]byte(input))
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	result = hash.Sum(nil)
	//or result = hash.Sum([]byte(""))
	fmt.Printf("%x\n\n", result)

	//End of input string test.

	//The input file test starts.

	input = "d:/Python.rar"
	filedata, err := os.Open(input)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	//MD5 algorithm.
	hash = md5.New()
	_, err = io.Copy(hash, filedata)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	result = hash.Sum(nil)
	//or result = hash.Sum([]byte(""))
	fmt.Printf("%x %s\n", result, input)

	//SHA1 algorithm.
	hash = sha1.New()
	_, err = io.Copy(hash, filedata)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	result = hash.Sum(nil)
	//or result = hash.Sum([]byte(""))
	fmt.Printf("%x %s\n", result, input)

	//SHA256 algorithm.
	hash = sha256.New()
	_, err = io.Copy(hash, filedata)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	result = hash.Sum(nil)
	//or result = hash.Sum([]byte(""))
	fmt.Printf("%x %s\n", result, input)

	//SHA512 algorithm.
	hash = sha512.New()
	_, err = io.Copy(hash, filedata)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	result = hash.Sum(nil)
	//or result = hash.Sum([]byte(""))
	fmt.Printf("%x %s\n", result, input)

	//End of input file test.

	//The program exits normally.
	os.Exit(0)
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326178106&siteId=291194637