github.com/searKing/golang/go@v1.2.117/crypto/sha256/sha256.go (about)

     1  // Copyright 2021 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sha256
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/sha256"
    10  	"encoding/hex"
    11  	"io"
    12  	"log"
    13  	"os"
    14  )
    15  
    16  func MySelf() ([]byte, error) {
    17  	f, err := os.Open(os.Args[0])
    18  	if err != nil {
    19  		log.Fatal(err)
    20  	}
    21  	defer f.Close()
    22  
    23  	h := sha256.New()
    24  	if _, err := io.Copy(h, f); err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	return h.Sum(nil), nil
    29  }
    30  
    31  func SumBytes(b []byte) []byte {
    32  	h := sha256.New()
    33  	h.Write(b)
    34  	return h.Sum(nil)
    35  }
    36  
    37  func SumString(b string) string {
    38  	return string(SumBytes([]byte(b)))
    39  }
    40  
    41  func SumHex(b string) string {
    42  	return hex.EncodeToString(SumBytes([]byte(b)))
    43  }
    44  
    45  func SumReader(r io.Reader) ([]byte, error) {
    46  	h := sha256.New()
    47  	if _, err := io.Copy(h, r); err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	return h.Sum(nil), nil
    52  }
    53  
    54  func SumFile(name string) ([]byte, error) {
    55  	f, err := os.Open(name)
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  	defer f.Close()
    60  	return SumReader(f)
    61  }
    62  
    63  func SumReaderAt(r io.ReaderAt, offset, size int64, buf []byte) ([]byte, error) {
    64  	h := sha256.New()
    65  	if len(buf) == 0 {
    66  		buf = make([]byte, 1024)
    67  	}
    68  
    69  	var total int64
    70  	for total < size {
    71  		n, err := r.ReadAt(buf, offset)
    72  		if err != nil {
    73  			return nil, err
    74  		}
    75  		offset += int64(n)
    76  		total += int64(n)
    77  		var copied int64
    78  		for copied < int64(n) {
    79  			copiedCount, err := io.CopyN(h, bytes.NewReader(buf), int64(n))
    80  			if err != nil {
    81  				return nil, err
    82  			}
    83  			copied += copiedCount
    84  		}
    85  	}
    86  
    87  	return h.Sum(nil), nil
    88  }
    89  
    90  // SumFileAt return ms5sum of data by offset and len is size
    91  // buf is a buffer to read from file every time.
    92  func SumFileAt(name string, offset, size int64, buf []byte) ([]byte, error) {
    93  	f, err := os.Open(name)
    94  	if err != nil {
    95  		return nil, err
    96  	}
    97  	defer f.Close()
    98  	return SumReaderAt(f, offset, size, buf)
    99  }