main.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "crypto/md5"
  17. "crypto/sha1"
  18. "crypto/sha256"
  19. "crypto/sha512"
  20. "fmt"
  21. "hash"
  22. "os"
  23. "strconv"
  24. "time"
  25. "yunion.io/x/onecloud/pkg/util/fileutils2"
  26. )
  27. func main() {
  28. if len(os.Args) < 2 {
  29. fmt.Printf("Usage: %s <file> [sample]\n", os.Args[0])
  30. return
  31. }
  32. names := []string{"MD5", "SHA1", "SHA256", "SHA512"}
  33. hashes := []hash.Hash{md5.New(), sha1.New(), sha256.New(), sha512.New()}
  34. start := time.Now()
  35. var sample int
  36. var err error
  37. if len(os.Args) > 2 {
  38. sample, err = strconv.Atoi(os.Args[2])
  39. if err != nil {
  40. fmt.Printf("illegal sample %s", err)
  41. return
  42. }
  43. }
  44. var results [][]byte
  45. if sample > 0 {
  46. results, err = fileutils2.FileFastHash(os.Args[1], hashes, sample)
  47. } else {
  48. results, err = fileutils2.FileHash(os.Args[1], hashes)
  49. }
  50. if err != nil {
  51. fmt.Printf("Error: %s", err)
  52. return
  53. }
  54. for i := 0; i < len(results); i += 1 {
  55. fmt.Printf("%s: %x\n", names[i], results[i])
  56. }
  57. sum := fileutils2.SumHashes(results)
  58. fmt.Printf("SUM: %x\n", sum)
  59. cost := time.Now().Sub(start)
  60. fmt.Printf("Time: %dms\n", cost/time.Millisecond)
  61. }