github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/gosbom/formats/common/util/h_digest.go (about)

     1  package util
     2  
     3  import (
     4  	"encoding/base64"
     5  	"encoding/hex"
     6  	"fmt"
     7  	"strings"
     8  )
     9  
    10  // HDigestToSHA converts a h# digest, such as h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= to an
    11  // algorithm such as sha256 and a hex encoded digest
    12  func HDigestToSHA(digest string) (string, string, error) {
    13  	// hash is base64, but we need hex encode
    14  	parts := strings.Split(digest, ":")
    15  	if len(parts) == 2 {
    16  		algo := parts[0]
    17  		hash := parts[1]
    18  		checksum, err := base64.StdEncoding.DecodeString(hash)
    19  		if err != nil {
    20  			return "", "", err
    21  		}
    22  
    23  		hexStr := hex.EncodeToString(checksum)
    24  
    25  		switch algo {
    26  		// golang h1 hash == sha256
    27  		case "h1":
    28  			algo = "sha256"
    29  		default:
    30  			return "", "", fmt.Errorf("unsupported h#digest algorithm: %s", algo)
    31  		}
    32  
    33  		return algo, hexStr, nil
    34  	}
    35  
    36  	return "", "", fmt.Errorf("invalid h#digest: %s", digest)
    37  }
    38  
    39  // HDigestFromSHA converts an algorithm, such sha256 with a hex encoded digest to a
    40  // h# value such as h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
    41  func HDigestFromSHA(algorithm string, digest string) (string, error) {
    42  	if digest == "" {
    43  		return "", fmt.Errorf("no digest value provided")
    44  	}
    45  	// digest is hex, but we need to base64 encode
    46  	algorithm = strings.ToLower(algorithm)
    47  	if algorithm == "sha256" {
    48  		checksum, err := hex.DecodeString(digest)
    49  		if err != nil {
    50  			return "", err
    51  		}
    52  		// hash is hex, but we need base64
    53  		b64digest := base64.StdEncoding.EncodeToString(checksum)
    54  		return fmt.Sprintf("h1:%s", b64digest), nil
    55  	}
    56  	return "", fmt.Errorf("not a recognized h#digest algorithm: %s", algorithm)
    57  }