cheksum.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 fileutils2
  15. import (
  16. "crypto/md5"
  17. "crypto/sha1"
  18. "crypto/sha256"
  19. "crypto/sha512"
  20. "fmt"
  21. "hash"
  22. "io"
  23. "os"
  24. "yunion.io/x/log"
  25. )
  26. func FileHash(filename string, hash []hash.Hash) ([][]byte, error) {
  27. fp, err := os.Open(filename)
  28. if err != nil {
  29. log.Errorf("open file for hash fail %s", err)
  30. return nil, err
  31. }
  32. defer fp.Close()
  33. buf := make([]byte, 4096)
  34. for {
  35. n, err := fp.Read(buf)
  36. if n > 0 {
  37. for i := 0; i < len(hash); i += 1 {
  38. hash[i].Write(buf[:n])
  39. }
  40. }
  41. if n == 0 || err == io.EOF {
  42. break
  43. }
  44. if err != nil {
  45. log.Errorf("read file error %s", err)
  46. return nil, err
  47. }
  48. }
  49. sums := make([][]byte, len(hash))
  50. for i := 0; i < len(hash); i += 1 {
  51. sums[i] = hash[i].Sum(nil)
  52. }
  53. return sums, nil
  54. }
  55. func MD5(filename string) (string, error) {
  56. sums, err := FileHash(filename, []hash.Hash{md5.New()})
  57. if err != nil {
  58. return "", err
  59. }
  60. return fmt.Sprintf("%x", sums[0]), nil
  61. }
  62. func SHA1(filename string) (string, error) {
  63. sums, err := FileHash(filename, []hash.Hash{sha1.New()})
  64. if err != nil {
  65. return "", err
  66. }
  67. return fmt.Sprintf("%x", sums[0]), nil
  68. }
  69. func SHA256(filename string) (string, error) {
  70. sums, err := FileHash(filename, []hash.Hash{sha256.New()})
  71. if err != nil {
  72. return "", err
  73. }
  74. return fmt.Sprintf("%x", sums[0]), nil
  75. }
  76. func SHA512(filename string) (string, error) {
  77. sums, err := FileHash(filename, []hash.Hash{sha512.New()})
  78. if err != nil {
  79. return "", err
  80. }
  81. return fmt.Sprintf("%x", sums[0]), nil
  82. }