github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/cmd/plugin/download/verifier.go (about) 1 // Copyright 2019 The Kubernetes 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 download 16 17 import ( 18 "bytes" 19 "crypto/sha256" 20 "encoding/hex" 21 "hash" 22 "io" 23 24 "github.com/pkg/errors" 25 "k8s.io/klog/v2" 26 ) 27 28 type Verifier interface { 29 io.Writer 30 Verify() error 31 } 32 33 var _ Verifier = sha256Verifier{} 34 35 type sha256Verifier struct { 36 hash.Hash 37 wantedHash []byte 38 } 39 40 // NewSha256Verifier creates a Verifier that tests against the given hash. 41 func NewSha256Verifier(hashed string) Verifier { 42 raw, _ := hex.DecodeString(hashed) 43 return sha256Verifier{ 44 Hash: sha256.New(), 45 wantedHash: raw, 46 } 47 } 48 49 func (v sha256Verifier) Verify() error { 50 klog.V(1).Infof("Compare sha256 (%s) signed version", hex.EncodeToString(v.wantedHash)) 51 if bytes.Equal(v.wantedHash, v.Sum(nil)) { 52 return nil 53 } 54 return errors.Errorf("checksum does not match, want: %x, got %x", v.wantedHash, v.Sum(nil)) 55 }