...

Source file src/github.com/sigstore/rekor/pkg/util/sha.go

Documentation: github.com/sigstore/rekor/pkg/util

     1  // Copyright 2022 The Sigstore 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 util
    16  
    17  import (
    18  	"crypto"
    19  	"fmt"
    20  	"strings"
    21  )
    22  
    23  // PrefixSHA sets the prefix of a sha hash to match how it is stored based on the length.
    24  func PrefixSHA(sha string) string {
    25  	var prefix string
    26  	var components = strings.Split(sha, ":")
    27  
    28  	if len(components) == 2 {
    29  		return sha
    30  	}
    31  
    32  	switch len(sha) {
    33  	case 40:
    34  		prefix = "sha1:"
    35  	case 64:
    36  		prefix = "sha256:"
    37  	case 96:
    38  		prefix = "sha384:"
    39  	case 128:
    40  		prefix = "sha512:"
    41  	}
    42  
    43  	return fmt.Sprintf("%v%v", prefix, sha)
    44  }
    45  
    46  func UnprefixSHA(sha string) (crypto.Hash, string) {
    47  	components := strings.Split(sha, ":")
    48  
    49  	if len(components) == 2 {
    50  		prefix := components[0]
    51  		sha = components[1]
    52  
    53  		switch prefix {
    54  		case "sha1":
    55  			return crypto.SHA1, sha
    56  		case "sha256":
    57  			return crypto.SHA256, sha
    58  		case "sha384":
    59  			return crypto.SHA384, sha
    60  		case "sha512":
    61  			return crypto.SHA512, sha
    62  		default:
    63  			return crypto.Hash(0), ""
    64  		}
    65  	}
    66  
    67  	switch len(sha) {
    68  	case 40:
    69  		return crypto.SHA1, sha
    70  	case 64:
    71  		return crypto.SHA256, sha
    72  	case 96:
    73  		return crypto.SHA384, sha
    74  	case 128:
    75  		return crypto.SHA512, sha
    76  	}
    77  
    78  	return crypto.Hash(0), ""
    79  }
    80  

View as plain text