github.com/dtroyer-salad/og2/v2@v2.0.0-20240412154159-c47231610877/content/verifiers.go (about)

     1  /*
     2  Copyright 2019, 2020 OCI Contributors
     3  Copyright 2017 Docker, Inc.
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package content
    18  
    19  import (
    20  	"hash"
    21  
    22  	"github.com/opencontainers/go-digest"
    23  )
    24  
    25  // Verifier returns a writer object that can be used to verify a stream of
    26  // content against the digest. If the digest is invalid, the method will panic.
    27  func Verifier(d digest.Digest) digest.Verifier {
    28  	return hashVerifier{
    29  		hash:   d.Algorithm().Hash(),
    30  		digest: d,
    31  	}
    32  }
    33  
    34  // Copied from https://github.com/opencontainers/go-digest/blob/master/verifiers.go
    35  // Since hashVerifier is non-public in go-digest and we need to supply a pre-initialized
    36  // Hash we'll just make our own. Thank you Verifier interface!
    37  
    38  type hashVerifier struct {
    39  	digest digest.Digest
    40  	hash   hash.Hash
    41  }
    42  
    43  func (hv hashVerifier) Write(p []byte) (n int, err error) {
    44  	return hv.hash.Write(p)
    45  }
    46  
    47  func (hv hashVerifier) Verified() bool {
    48  	return hv.digest == digest.NewDigest(hv.digest.Algorithm(), hv.hash)
    49  }