md5_checksum.go raw

   1  package http
   2  
   3  import (
   4  	"crypto/md5"
   5  	"encoding/base64"
   6  	"fmt"
   7  	"io"
   8  )
   9  
  10  // computeMD5Checksum computes base64 md5 checksum of an io.Reader's contents.
  11  // Returns the byte slice of md5 checksum and an error.
  12  func computeMD5Checksum(r io.Reader) ([]byte, error) {
  13  	h := md5.New()
  14  	// copy errors may be assumed to be from the body.
  15  	_, err := io.Copy(h, r)
  16  	if err != nil {
  17  		return nil, fmt.Errorf("failed to read body: %w", err)
  18  	}
  19  
  20  	// encode the md5 checksum in base64.
  21  	sum := h.Sum(nil)
  22  	sum64 := make([]byte, base64.StdEncoding.EncodedLen(len(sum)))
  23  	base64.StdEncoding.Encode(sum64, sum)
  24  	return sum64, nil
  25  }
  26