github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/builder/azure/common/randomstring.go (about)

     1  // Copyright (c) Microsoft Corporation. All rights reserved.
     2  // Licensed under the MIT License. See the LICENSE file in builder/azure for license information.
     3  
     4  package common
     5  
     6  import (
     7  	"math/rand"
     8  	"os"
     9  	"time"
    10  )
    11  
    12  var pwSymbols = []string{
    13  	"abcdefghijklmnopqrstuvwxyz",
    14  	"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
    15  	"0123456789",
    16  }
    17  
    18  var rnd = rand.New(rand.NewSource(time.Now().UnixNano() + int64(os.Getpid())))
    19  
    20  func RandomString(chooseFrom string, length int) (randomString string) {
    21  	cflen := len(chooseFrom)
    22  	for i := 0; i < length; i++ {
    23  		randomString += string(chooseFrom[rnd.Intn(cflen)])
    24  	}
    25  	return
    26  }
    27  
    28  func RandomPassword() (password string) {
    29  	pwlen := 15
    30  	batchsize := pwlen / len(pwSymbols)
    31  	pw := make([]byte, 0, pwlen)
    32  	// choose character set
    33  	for c := 0; len(pw) < pwlen; c++ {
    34  		s := RandomString(pwSymbols[c%len(pwSymbols)], rnd.Intn(batchsize-1)+1)
    35  		pw = append(pw, []byte(s)...)
    36  	}
    37  	// truncate
    38  	pw = pw[:pwlen]
    39  
    40  	// permute
    41  	for c := 0; c < pwlen-1; c++ {
    42  		i := rnd.Intn(pwlen-c) + c
    43  		x := pw[c]
    44  		pw[c] = pw[i]
    45  		pw[i] = x
    46  	}
    47  	return string(pw)
    48  }