github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/cmds/core/shasum/shasum.go (about)

     1  // Copyright 2018 the u-root Authors. 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 main
     6  
     7  import (
     8  	"crypto/sha1"
     9  	"crypto/sha256"
    10  	"fmt"
    11  	"io/ioutil"
    12  	"os"
    13  
    14  	"github.com/spf13/pflag"
    15  )
    16  
    17  func helpPrinter() {
    18  
    19  	fmt.Printf("Usage:\nshasum -a <algorithm> <File Name>\n")
    20  	pflag.PrintDefaults()
    21  	os.Exit(0)
    22  }
    23  
    24  func versionPrinter() {
    25  	fmt.Println("shasum utility, URoot Version.")
    26  	os.Exit(0)
    27  }
    28  
    29  func getInput(fileName string) (input []byte, err error) {
    30  
    31  	if fileName != "" {
    32  		return ioutil.ReadFile(fileName)
    33  	}
    34  	return ioutil.ReadAll(os.Stdin)
    35  }
    36  
    37  //
    38  // shaPrinter prints sha1/sha256 of given data. The
    39  // value of algorithm is expected to be 1 for SHA1
    40  // and 256 for SHA256
    41  //
    42  func shaPrinter(algorithm int, data []byte) string {
    43  	var sha string
    44  	if algorithm == 256 {
    45  		sha = fmt.Sprintf("%x", sha256.Sum256(data))
    46  	} else if algorithm == 1 {
    47  		sha = fmt.Sprintf("%x", sha1.Sum(data))
    48  	} else {
    49  		fmt.Fprintf(os.Stderr, "Invalid algorithm")
    50  		return ""
    51  	}
    52  	return sha
    53  }
    54  
    55  func main() {
    56  
    57  	var (
    58  		algorithm int
    59  		help      bool
    60  		version   bool
    61  	)
    62  	cliArgs := ""
    63  	pflag.IntVarP(&algorithm, "algorithm", "a", 1, "SHA algorithm, valid args are 1 and 256")
    64  	pflag.BoolVarP(&help, "help", "h", false, "Show this help and exit")
    65  	pflag.BoolVarP(&version, "version", "v", false, "Print Version")
    66  	pflag.Parse()
    67  
    68  	if help {
    69  		helpPrinter()
    70  	}
    71  
    72  	if version {
    73  		versionPrinter()
    74  	}
    75  	if len(pflag.Args()) == 1 {
    76  		cliArgs = pflag.Args()[0]
    77  	}
    78  	input, err := getInput(cliArgs)
    79  	if err != nil {
    80  		fmt.Println("Error getting input.")
    81  		os.Exit(-1)
    82  	}
    83  	fmt.Printf("%s ", shaPrinter(algorithm, input))
    84  	if cliArgs == "" {
    85  		fmt.Printf(" -\n")
    86  	} else {
    87  		fmt.Printf(" %s\n", cliArgs)
    88  	}
    89  	os.Exit(0)
    90  }