ComputeFileChecksum computes the checksum of the specified file based on the specified algorithm
(filePath, algorithm string)
| 15 | |
| 16 | // ComputeFileChecksum computes the checksum of the specified file based on the specified algorithm |
| 17 | func ComputeFileChecksum(filePath, algorithm string) (string, error) { |
| 18 | var hasher hash.Hash |
| 19 | switch strings.ToUpper(algorithm) { |
| 20 | case "MD5": |
| 21 | hasher = md5.New() |
| 22 | case "SHA1": |
| 23 | hasher = sha1.New() |
| 24 | case "SHA256": |
| 25 | hasher = sha256.New() |
| 26 | case "SHA512": |
| 27 | hasher = sha512.New() |
| 28 | default: |
| 29 | return "", fmt.Errorf("Unsupported digest algorithm %q", algorithm) |
| 30 | } |
| 31 | |
| 32 | file, err := os.Open(filePath) |
| 33 | if err != nil { |
| 34 | return "", err |
| 35 | } |
| 36 | defer file.Close() |
| 37 | |
| 38 | _, err = io.Copy(hasher, file) |
| 39 | if err != nil { |
| 40 | return "", err |
| 41 | } |
| 42 | return hex.EncodeToString(hasher.Sum(nil)), nil |
| 43 | } |
no test coverage detected