vitess.io/vitess@v0.16.2/go/vt/vtorc/util/token.go (about)

     1  /*
     2     Copyright 2014 Outbrain Inc.
     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 util
    18  
    19  import (
    20  	"crypto/rand"
    21  	"crypto/sha256"
    22  	"encoding/hex"
    23  	"fmt"
    24  	"time"
    25  )
    26  
    27  const (
    28  	shortTokenLength = 8
    29  )
    30  
    31  func toHash(input []byte) string {
    32  	hasher := sha256.New()
    33  	hasher.Write(input)
    34  	return hex.EncodeToString(hasher.Sum(nil))
    35  }
    36  
    37  func getRandomData() []byte {
    38  	size := 64
    39  	rb := make([]byte, size)
    40  	_, _ = rand.Read(rb)
    41  	return rb
    42  }
    43  
    44  func RandomHash() string {
    45  	return toHash(getRandomData())
    46  }
    47  
    48  // Token is used to identify and validate requests to this service
    49  type Token struct {
    50  	Hash string
    51  }
    52  
    53  func (token *Token) Short() string {
    54  	if len(token.Hash) <= shortTokenLength {
    55  		return token.Hash
    56  	}
    57  	return token.Hash[0:shortTokenLength]
    58  }
    59  
    60  var ProcessToken = NewToken()
    61  
    62  func NewToken() *Token {
    63  	return &Token{
    64  		Hash: RandomHash(),
    65  	}
    66  }
    67  
    68  func PrettyUniqueToken() string {
    69  	return fmt.Sprintf("%d:%s", time.Now().UnixNano(), NewToken().Hash)
    70  }