matrix-appservice-go

git clone git://archive.git.mtrnord.blog/MTRNord/matrix-appservice-go.git
Log | Files | Refs | README

utils.go (1001B)


      1 package utils
      2 
      3 import (
      4 	"crypto/rand"
      5 	"log"
      6 )
      7 
      8 const (
      9 	letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // 52 possibilities
     10 	letterIdxBits = 6                    // 6 bits to represent 64 possibilities / indexes
     11 	letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
     12 )
     13 
     14 func RandomString(length int) string {
     15 
     16 	result := make([]byte, length)
     17 	bufferSize := int(float64(length)*1.3)
     18 	for i, j, randomBytes := 0, 0, []byte{}; i < length; j++ {
     19 		if j%bufferSize == 0 {
     20 			randomBytes = SecureRandomBytes(bufferSize)
     21 		}
     22 		if idx := int(randomBytes[j%length] & letterIdxMask); idx < len(letterBytes) {
     23 			result[i] = letterBytes[idx]
     24 			i++
     25 		}
     26 	}
     27 
     28 	return string(result)
     29 }
     30 
     31 // SecureRandomBytes returns the requested number of bytes using crypto/rand
     32 func SecureRandomBytes(length int) []byte {
     33 	var randomBytes = make([]byte, length)
     34 	_, err := rand.Read(randomBytes)
     35 	if err != nil {
     36 		log.Fatal("Unable to generate random bytes")
     37 	}
     38 	return randomBytes
     39 }