github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/utils/hash/md5.go (about)

     1  // Copyright © 2021 Alibaba Group Holding Ltd.
     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  
    15  package hash
    16  
    17  import (
    18  	"crypto/md5" // #nosec
    19  	"encoding/hex"
    20  	"fmt"
    21  	"io"
    22  	"os"
    23  	"path/filepath"
    24  )
    25  
    26  func MD5(body []byte) string {
    27  	bytes := md5.Sum(body) // #nosec
    28  	return hex.EncodeToString(bytes[:])
    29  }
    30  
    31  // FileMD5 count file md5
    32  func FileMD5(path string) (string, error) {
    33  	file, err := os.Open(filepath.Clean(path))
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  
    38  	m := md5.New() // #nosec
    39  	if _, err := io.Copy(m, file); err != nil {
    40  		return "", err
    41  	}
    42  
    43  	fileMd5 := fmt.Sprintf("%x", m.Sum(nil))
    44  	return fileMd5, nil
    45  }