code.gitea.io/gitea@v1.19.3/modules/avatar/hash.go (about)

     1  // Copyright 2023 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package avatar
     5  
     6  import (
     7  	"crypto/sha256"
     8  	"encoding/hex"
     9  	"strconv"
    10  )
    11  
    12  // HashAvatar will generate a unique string, which ensures that when there's a
    13  // different unique ID while the data is the same, it will generate a different
    14  // output. It will generate the output according to:
    15  // HEX(HASH(uniqueID || - || data))
    16  // The hash being used is SHA256.
    17  // The sole purpose of the unique ID is to generate a distinct hash Such that
    18  // two unique IDs with the same data will have a different hash output.
    19  // The "-" byte is important to ensure that data cannot be modified such that
    20  // the first byte is a number, which could lead to a "collision" with the hash
    21  // of another unique ID.
    22  func HashAvatar(uniqueID int64, data []byte) string {
    23  	h := sha256.New()
    24  	h.Write([]byte(strconv.FormatInt(uniqueID, 10)))
    25  	h.Write([]byte{'-'})
    26  	h.Write(data)
    27  	return hex.EncodeToString(h.Sum(nil))
    28  }