go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cipd/appengine/impl/metadata/fingerprint.go (about)

     1  // Copyright 2018 The LUCI Authors.
     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 metadata
    16  
    17  import (
    18  	"crypto/sha1"
    19  	"encoding/base64"
    20  	"fmt"
    21  
    22  	"google.golang.org/protobuf/proto"
    23  
    24  	api "go.chromium.org/luci/cipd/api/cipd/v1"
    25  )
    26  
    27  // CalculateFingerprint fills in Fingerprint field of the given metadata.
    28  //
    29  // It is basically base64-encoded SHA1 digest of the serialized proto
    30  // (excluding 'fingerprint' field itself). It doesn't have to be
    31  // cryptographically secure.
    32  //
    33  // Note that it is also fine if the proto encoding changes with time. We don't
    34  // care about exact meaning of the fingerprint, as long as it changes each time
    35  // we update the metadata (so strictly speaking we can just generate random
    36  // strings and call them fingerprints).
    37  func CalculateFingerprint(m *api.PrefixMetadata) {
    38  	m.Fingerprint = ""
    39  	blob, err := proto.Marshal(m)
    40  	if err != nil {
    41  		panic(fmt.Sprintf("failed to proto-marshal PrefixMetadata for prefix %q - %s", m.Prefix, err))
    42  	}
    43  	h := sha1.New()
    44  	h.Write([]byte("PrefixMetadata:"))
    45  	h.Write(blob)
    46  	m.Fingerprint = base64.RawURLEncoding.EncodeToString(h.Sum(nil))
    47  }