vitess.io/vitess@v0.16.2/go/textutil/hash.go (about)

     1  /*
     2  Copyright 2020 The Vitess Authors.
     3  
     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 textutil
    18  
    19  import (
    20  	"crypto/rand"
    21  	"crypto/sha256"
    22  	"encoding/hex"
    23  	"fmt"
    24  	"math/big"
    25  	"strings"
    26  
    27  	"github.com/google/uuid"
    28  )
    29  
    30  const (
    31  	randomHashSize = 64
    32  )
    33  
    34  // RandomHash returns a 64 hex character random string
    35  func RandomHash() string {
    36  	rb := make([]byte, randomHashSize)
    37  	_, _ = rand.Read(rb)
    38  
    39  	hasher := sha256.New()
    40  	hasher.Write(rb)
    41  	return hex.EncodeToString(hasher.Sum(nil))
    42  }
    43  
    44  // uuidv5 creates a UUID v5 string based on the given inputs. We use a SHA256 algorithm.
    45  func uuidv5(inputs ...string) uuid.UUID {
    46  	var baseUUID uuid.UUID
    47  	input := strings.Join(inputs, "\n")
    48  	return uuid.NewHash(sha256.New(), baseUUID, []byte(input), 5)
    49  }
    50  
    51  // UUIDv5 creates a UUID v5 string based on the given inputs. We use a SHA256 algorithm. Return format is textual
    52  func UUIDv5(inputs ...string) string {
    53  	return uuidv5(inputs...).String()
    54  }
    55  
    56  // UUIDv5Var creeates a UUID v5 string based on the given inputs. Return value is a big.Int
    57  func UUIDv5Val(inputs ...string) big.Int {
    58  	u := uuidv5(inputs...)
    59  	var i big.Int
    60  	i.SetBytes(u[:])
    61  	return i
    62  }
    63  
    64  // UUIDv5Base36 creeates a UUID v5 string based on the given inputs. Return value is a 25 character, base36 string
    65  func UUIDv5Base36(inputs ...string) string {
    66  	i := UUIDv5Val(inputs...)
    67  	return fmt.Sprintf("%025s", i.Text(36))
    68  }