Created
December 22, 2021 23:43
-
-
Save looselycoupled/18a0f7f01be98958f9562d7e5e8ebfd6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/sha256" | |
"encoding/hex" | |
"fmt" | |
log "github.com/sirupsen/logrus" | |
"github.com/urfave/cli/v2" | |
"io" | |
"os" | |
) | |
func main() { | |
app := &cli.App{ | |
Usage: "a cli to calculate a hash chain but tediously", | |
Flags: []cli.Flag{}, | |
Commands: []*cli.Command{ | |
{ | |
Name: "add", | |
Aliases: []string{"a"}, | |
Usage: "returns a new hash based on an (optional) previous hash and the specified files", | |
Action: func(c *cli.Context) error { | |
if c.NArg() < 1 { | |
return fmt.Errorf("must specify at least one file") | |
} | |
hash, err := add(c.String("previous"), c.Args().Slice()) | |
if err != nil { | |
return err | |
} | |
fmt.Printf("%x\n", hash) | |
return nil | |
}, | |
Flags: []cli.Flag{ | |
&cli.StringFlag{ | |
Name: "previous", | |
Aliases: []string{"p"}, | |
Usage: "previous hash for hash chain", | |
DefaultText: "", | |
}, | |
}, | |
}, | |
}, | |
} | |
err := app.Run(os.Args) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func add (previous string, files []string) ([]byte, error) { | |
var err error | |
var hashes []byte | |
if previous != "" { | |
hashes, err = hex.DecodeString(previous) | |
if err != nil { | |
return nil, err | |
} | |
} | |
for _, f := range files { | |
hashes, err = appendFileHash(hashes, f) | |
if err != nil { | |
return nil, err | |
} | |
log.Infof("file: %s", f) | |
} | |
hash := sha256.New() | |
hash.Write(hashes) | |
return hash.Sum(nil), nil | |
} | |
func appendFileHash(hash []byte, path string) ([]byte, error) { | |
f, err := os.Open(path) | |
if err != nil { | |
return nil, err | |
} | |
defer f.Close() | |
h := sha256.New() | |
if _, err := io.Copy(h, f); err != nil { | |
return nil, err | |
} | |
return h.Sum(hash), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment