github.com/joey-fossa/fossa-cli@v0.7.34-0.20190708193710-569f1e8679f0/analyzers/ant/hashes.go (about)

     1  package ant
     2  
     3  import (
     4  	"bufio"
     5  	"crypto/md5" // nolint: gas
     6  	"crypto/sha1"
     7  	"crypto/sha256"
     8  	"encoding/hex"
     9  	"io"
    10  	"os"
    11  
    12  	"github.com/fossas/fossa-cli/module"
    13  )
    14  
    15  // GetHashes computes hexadecimal checksums of a variety of types for a given file path
    16  func GetHashes(path string) (module.Hashes, error) {
    17  	hashes := module.Hashes{}
    18  
    19  	f, err := os.Open(path)
    20  	if err != nil {
    21  		return hashes, err
    22  	}
    23  	defer f.Close()
    24  
    25  	md5 := md5.New() // nolint: gas
    26  	sha1 := sha1.New()
    27  	sha256 := sha256.New()
    28  
    29  	// Read the file once and write to a multiplexer
    30  	// so we can calculate all hashes simultaneously
    31  	pagesize := os.Getpagesize()
    32  	reader := bufio.NewReaderSize(f, pagesize)
    33  	multiWriter := io.MultiWriter(md5, sha1, sha256)
    34  	if _, err := io.Copy(multiWriter, reader); err != nil {
    35  		panic(err.Error())
    36  	}
    37  
    38  	hashes.MD5 = hex.EncodeToString(md5.Sum(nil))
    39  	hashes.SHA1 = hex.EncodeToString(sha1.Sum(nil))
    40  	hashes.SHA256 = hex.EncodeToString(sha256.Sum(nil))
    41  
    42  	return hashes, err
    43  }