Skip to content

Commit

Permalink
Add randBytes
Browse files Browse the repository at this point in the history
Adds the randBytes function to cryptographically generate a
base64-encoded string of random bytes of a given length.

Resolves #252.
  • Loading branch information
MikaelSmith committed Nov 30, 2020
1 parent 0a555ee commit f0c2324
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
8 changes: 8 additions & 0 deletions crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ func htpasswd(username string, password string) string {
return fmt.Sprintf("%s:%s", username, hash)
}

func randBytes(count int) (string, error) {
buf := make([]byte, count)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(buf), nil
}

// uuidv4 provides a safe and secure UUID v4 implementation
func uuidv4() string {
return uuid.New().String()
Expand Down
25 changes: 25 additions & 0 deletions crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,31 @@ func TestGenPrivateKey(t *testing.T) {
}
}

func TestRandBytes(t *testing.T) {
tpl := `{{randBytes 12}}`
out, err := runRaw(tpl, nil)
if err != nil {
t.Error(err)
}

bytes, err := base64.StdEncoding.DecodeString(out)
if err != nil {
t.Error(err)
}
if len(bytes) != 12 {
t.Error("Expected 12 base64-encoded bytes")
}

out2, err := runRaw(tpl, nil)
if err != nil {
t.Error(err)
}

if out == out2 {
t.Error("Expected subsequent randBytes to be different")
}
}

func TestUUIDGeneration(t *testing.T) {
tpl := `{{uuidv4}}`
out, err := runRaw(tpl, nil)
Expand Down
10 changes: 10 additions & 0 deletions docs/crypto.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ htpasswd "myUser" "myPassword"

Note that it is insecure to store the password directly in the template.

## randBytes

The `randBytes` function accepts a count `N` and generates a cryptographically
secure (uses ```crypto/rand```) random sequence of `N` bytes. The sequence is
returned as a base64 encoded string.

```
randBytes 24
```

## derivePassword

The `derivePassword` function can be used to derive a specific password based on
Expand Down
2 changes: 2 additions & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ var nonhermeticFunctions = []string{
"randAlpha",
"randAscii",
"randNumeric",
"randBytes",
"uuidv4",

// OS
Expand Down Expand Up @@ -308,6 +309,7 @@ var genericMap = map[string]interface{}{
"genSignedCert": generateSignedCertificate,
"encryptAES": encryptAES,
"decryptAES": decryptAES,
"randBytes": randBytes,

// UUIDs:
"uuidv4": uuidv4,
Expand Down

0 comments on commit f0c2324

Please sign in to comment.