Skip to content

Commit

Permalink
Merge pull request #2 from brianasapp/bd/crypto-rand
Browse files Browse the repository at this point in the history
make cryptographically secure randoms the default
  • Loading branch information
brianasapp authored Aug 4, 2017
2 parents f079793 + e5c73c2 commit d9f7b4c
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# sputter

_WARNING: I AM NOT CRYPTO FRIENDLY_

POSIX basic regular expressions to psuedo random string generator, just for fun :)

### Usage
Expand Down Expand Up @@ -31,6 +29,8 @@ WordWord
Њѯѹկ¢↔≡♲
```

_For cryptographically insecure usage, use the `GenInsecure` function in place of `Gen`_



### Supported Operations
Expand Down
24 changes: 22 additions & 2 deletions sputter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package sputter

import (
"bytes"
crypto "crypto/rand"
"fmt"
"math/big"
"math/rand"
"regexp/syntax"
"time"
Expand All @@ -11,15 +13,33 @@ import (

const (
repetitionMax = 100
maxUint64 = ^uint64(0)
maxInt64 = int64(maxUint64 >> 1)
)

func init() {
rand.Seed(time.Now().UTC().UnixNano())
}

// Gen takes a regular expression and attempts
// to generate a pseudo-randomized string that
// matches the input expression.
func Gen(exp string) (string, error) {
// setup random package
rand.Seed(time.Now().UTC().UnixNano())
// cryptographically seed random package
bigSeed, err := crypto.Int(crypto.Reader, big.NewInt(maxInt64))
if err != nil {
return "", err
}
rand.Seed(bigSeed.Int64())

r, err := syntax.Parse(exp, 0)
if err != nil {
return "", err
}
return sput(r)
}

func GenInsecure(exp string) (string, error) {
r, err := syntax.Parse(exp, 0)
if err != nil {
return "", err
Expand Down
18 changes: 18 additions & 0 deletions sputter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func TestEndLine(t *testing.T) {
}

func testSputHundredEmoji(t *testing.T, exp string) {
// test cryptographically secure function 100 times
for i := 0; i < 100; i++ {
s, err := Gen(exp)
if err != nil {
Expand All @@ -77,4 +78,21 @@ func testSputHundredEmoji(t *testing.T, exp string) {
t.Error(err)
}
}

// do same for cryptographically insecure function
for i := 0; i < 100; i++ {
s, err := GenInsecure(exp)
if err != nil {
t.Error(`error from Gen:`, err)
}

match, err := regexp.Match(exp, []byte(s))
if !match {
t.Errorf(`output string "%s" does not match expression "%s"`, s, exp)
}

if err != nil {
t.Error(err)
}
}
}

0 comments on commit d9f7b4c

Please sign in to comment.