Skip to content
This repository has been archived by the owner on Feb 16, 2023. It is now read-only.

Commit

Permalink
Merge pull request #13 from keylockerbv/randstr
Browse files Browse the repository at this point in the history
Move the core/random package to secrethub-go/pkg/randstr
  • Loading branch information
SimonBarendse committed Feb 12, 2019
2 parents d6c7cfe + 89e43d7 commit 9e9c0a6
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
14 changes: 14 additions & 0 deletions pkg/randstr/fakes/generator.go
@@ -0,0 +1,14 @@
// +build !production

package fakes

// FakeRandomGenerator can be used to mock a RandomGenerator.
type FakeRandomGenerator struct {
Ret []byte
Err error
}

// Generate returns the mocked Generate response.
func (generator FakeRandomGenerator) Generate(length int) ([]byte, error) {
return generator.Ret, generator.Err
}
54 changes: 54 additions & 0 deletions pkg/randstr/generator.go
@@ -0,0 +1,54 @@
package randstr

import (
"crypto/rand"
"math/big"

"github.com/keylockerbv/secrethub-go/pkg/errio"
)

var (
// randPatternAlphanumeric is the default pattern of characters used to generate random secrets.
randPatternAlphanumeric = []byte(`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`)
// randPatternSymbols is added to the randPattern when generator.useSymbols is true.
randPatternSymbols = []byte(`!@#$%^*-_+=.,?`)
)

// Generator generates random byte arrays.
type Generator interface {
Generate(length int) ([]byte, error)
}

// NewGenerator creates a new random generator.
func NewGenerator(useSymbols bool) Generator {
return &generator{
useSymbols: useSymbols,
}
}

type generator struct {
useSymbols bool
}

// Generate returns a random byte array of given length.
func (generator generator) Generate(length int) ([]byte, error) {
pattern := randPatternAlphanumeric
if generator.useSymbols {
pattern = append(pattern, randPatternSymbols...)
}
return randFromPattern(pattern, length)
}

func randFromPattern(pattern []byte, length int) ([]byte, error) {
data := make([]byte, length)

lengthPattern := len(pattern)
for i := 0; i < length; i++ {
c, err := rand.Int(rand.Reader, big.NewInt(int64(lengthPattern)))
if err != nil {
return nil, errio.Error(err)
}
data[i] = pattern[c.Int64()]
}
return data, nil
}

0 comments on commit 9e9c0a6

Please sign in to comment.