go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/connection/fs/fsutil/hash.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package fsutil
     5  
     6  import (
     7  	"crypto/md5"
     8  	"crypto/sha256"
     9  	"encoding/hex"
    10  	"io"
    11  
    12  	"github.com/spf13/afero"
    13  )
    14  
    15  func Md5(f afero.File) (string, error) {
    16  	h := md5.New()
    17  	if _, err := io.Copy(h, f); err != nil {
    18  		return "", err
    19  	}
    20  
    21  	return hex.EncodeToString(h.Sum(nil)), nil
    22  }
    23  
    24  func Sha256(f afero.File) (string, error) {
    25  	h := sha256.New()
    26  	if _, err := io.Copy(h, f); err != nil {
    27  		return "", err
    28  	}
    29  
    30  	return hex.EncodeToString(h.Sum(nil)), nil
    31  }
    32  
    33  // LocalFileSha256 determines the hashsum for a local file
    34  func LocalFileSha256(filename string) (string, error) {
    35  	osFs := afero.NewOsFs()
    36  	f, err := osFs.Open(filename)
    37  	if err != nil {
    38  		return "", err
    39  	}
    40  
    41  	defer f.Close()
    42  	hash, err := Sha256(f)
    43  	if err != nil {
    44  		return "", err
    45  	}
    46  	return hash, nil
    47  }