github.com/thanhphan1147/cloudfoundry-cli@v7.1.0+incompatible/util/checksum.go (about)

     1  package util
     2  
     3  import (
     4  	"crypto/sha1"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  )
     9  
    10  //go:generate counterfeiter . Sha1Checksum
    11  
    12  type Sha1Checksum interface {
    13  	ComputeFileSha1() ([]byte, error)
    14  	CheckSha1(string) bool
    15  	SetFilePath(string)
    16  }
    17  
    18  type sha1Checksum struct {
    19  	filepath string
    20  }
    21  
    22  func NewSha1Checksum(filepath string) Sha1Checksum {
    23  	return &sha1Checksum{
    24  		filepath: filepath,
    25  	}
    26  }
    27  
    28  func (c *sha1Checksum) CheckSha1(targetSha1 string) bool {
    29  	sha1, err := c.ComputeFileSha1()
    30  	if err != nil {
    31  		return false
    32  	}
    33  
    34  	if fmt.Sprintf("%x", sha1) == targetSha1 {
    35  		return true
    36  	}
    37  	return false
    38  }
    39  
    40  func (c *sha1Checksum) ComputeFileSha1() ([]byte, error) {
    41  	hash := sha1.New()
    42  
    43  	f, err := os.Open(c.filepath)
    44  	if err != nil {
    45  		return []byte{}, err
    46  	}
    47  	defer f.Close()
    48  
    49  	if _, err := io.Copy(hash, f); err != nil {
    50  		return []byte{}, err
    51  	}
    52  
    53  	return hash.Sum(nil), nil
    54  }
    55  
    56  func (c *sha1Checksum) SetFilePath(filepath string) {
    57  	c.filepath = filepath
    58  }