github.phpd.cn/cilium/cilium@v1.6.12/pkg/crypto/sha1/sha1.go (about) 1 // Copyright 2019 Authors of Cilium 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 sha1 16 17 import ( 18 "crypto/sha1" 19 "encoding" 20 "encoding/hex" 21 "fmt" 22 "hash" 23 ) 24 25 // ResumableHash is the intefrace for a hash that can be stored and copied. 26 // 27 // Unlike hash implementations in the standard library, it does not implement 28 // the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler interfaces; 29 // however, it does provide a method for creating a copy of the underlying 30 // hash. This allows the hash to be stored, duplicated, and resumed at a later 31 // time. For convenience, it also provides a standard method for converting 32 // the hash into a string. 33 type ResumableHash interface { 34 hash.Hash 35 fmt.Stringer 36 Copy() (ResumableHash, error) 37 } 38 39 // digest is a wrapper for the standard sha1 library which implements 40 // ResumableHash. 41 type digest struct { 42 hash.Hash 43 } 44 45 // New returns a new ResumableHash computing the SHA1 checksum. 46 func New() ResumableHash { 47 return &digest{ 48 sha1.New(), 49 } 50 } 51 52 // Copy duplicates the hash and returns the copy. 53 func (d *digest) Copy() (ResumableHash, error) { 54 newHash := hash.Hash(sha1.New()) 55 state, err := d.Hash.(encoding.BinaryMarshaler).MarshalBinary() 56 if err != nil { 57 return nil, err 58 } 59 if err := newHash.(encoding.BinaryUnmarshaler).UnmarshalBinary(state); err != nil { 60 return nil, err 61 } 62 return &digest{ 63 newHash, 64 }, nil 65 } 66 67 // String returns a string representation of the underlying hash. 68 func (d *digest) String() string { 69 return hex.EncodeToString(d.Sum(nil)) 70 }