...

Source file src/sigs.k8s.io/release-utils/hash/hash.go

Documentation: sigs.k8s.io/release-utils/hash

     1  /*
     2  Copyright 2021 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package hash
    18  
    19  import (
    20  	"crypto/sha1" //nolint: gosec
    21  	"crypto/sha256"
    22  	"crypto/sha512"
    23  	"encoding/hex"
    24  	"errors"
    25  	"fmt"
    26  	"hash"
    27  	"io"
    28  	"os"
    29  
    30  	"github.com/sirupsen/logrus"
    31  )
    32  
    33  // SHA512ForFile returns the hex-encoded sha512 hash for the provided filename.
    34  func SHA512ForFile(filename string) (string, error) {
    35  	return ForFile(filename, sha512.New())
    36  }
    37  
    38  // SHA256ForFile returns the hex-encoded sha256 hash for the provided filename.
    39  func SHA256ForFile(filename string) (string, error) {
    40  	return ForFile(filename, sha256.New())
    41  }
    42  
    43  // SHA1ForFile returns the hex-encoded sha1 hash for the provided filename.
    44  // TODO: check if we can remove this function
    45  func SHA1ForFile(filename string) (string, error) {
    46  	return ForFile(filename, sha1.New()) //nolint: gosec
    47  }
    48  
    49  // ForFile returns the hex-encoded hash for the provided filename and hasher.
    50  func ForFile(filename string, hasher hash.Hash) (string, error) {
    51  	if hasher == nil {
    52  		return "", errors.New("provided hasher is nil")
    53  	}
    54  
    55  	f, err := os.Open(filename)
    56  	if err != nil {
    57  		return "", fmt.Errorf("open file %s: %w", filename, err)
    58  	}
    59  	defer func() {
    60  		if err := f.Close(); err != nil {
    61  			logrus.Warnf("Unable to close file %q: %v", filename, err)
    62  		}
    63  	}()
    64  
    65  	hasher.Reset()
    66  	if _, err := io.Copy(hasher, f); err != nil {
    67  		return "", fmt.Errorf("hash file %s: %w", filename, err)
    68  	}
    69  
    70  	return hex.EncodeToString(hasher.Sum(nil)), nil
    71  }
    72  

View as plain text