Skip to content

Commit

Permalink
Add crypto.randomBytes (#922)
Browse files Browse the repository at this point in the history
  • Loading branch information
bookmoons authored and mstoykov committed Feb 13, 2019
1 parent 9af59bc commit fb4d0ce
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
13 changes: 13 additions & 0 deletions js/modules/k6/crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"context"
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
Expand All @@ -50,6 +51,18 @@ func New() *Crypto {
return &Crypto{}
}

func (*Crypto) RandomBytes(ctx context.Context, size int) []byte {
if size < 1 {
common.Throw(common.GetRuntime(ctx), errors.New("Invalid size"))
}
bytes := make([]byte, size)
_, err := rand.Read(bytes)
if err != nil {
common.Throw(common.GetRuntime(ctx), err)
}
return bytes
}

func (c *Crypto) Md4(ctx context.Context, input []byte, outputEncoding string) string {
hasher := c.CreateHash(ctx, "md4")
hasher.Update(input)
Expand Down
35 changes: 35 additions & 0 deletions js/modules/k6/crypto/crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ package crypto

import (
"context"
"crypto/rand"
"errors"
"testing"

"github.com/dop251/goja"
Expand All @@ -30,6 +32,12 @@ import (
"github.com/stretchr/testify/assert"
)

type MockReader struct{}

func (MockReader) Read(p []byte) (n int, err error) {
return -1, errors.New("Contrived failure")
}

func TestCryptoAlgorithms(t *testing.T) {
if testing.Short() {
return
Expand All @@ -41,6 +49,33 @@ func TestCryptoAlgorithms(t *testing.T) {
ctx = common.WithRuntime(ctx, rt)
rt.Set("crypto", common.Bind(rt, New(), &ctx))

t.Run("RandomBytesSuccess", func(t *testing.T) {
_, err := common.RunString(rt, `
let bytes = crypto.randomBytes(5);
if (bytes.length !== 5) {
throw new Error("Incorrect size: " + bytes.length);
}`)

assert.NoError(t, err)
})

t.Run("RandomBytesInvalidSize", func(t *testing.T) {
_, err := common.RunString(rt, `
crypto.randomBytes(-1);`)

assert.Error(t, err)
})

t.Run("RandomBytesFailure", func(t *testing.T) {
SavedReader := rand.Reader
rand.Reader = MockReader{}
_, err := common.RunString(rt, `
crypto.randomBytes(5);`)
rand.Reader = SavedReader

assert.Error(t, err)
})

t.Run("MD4", func(t *testing.T) {
_, err := common.RunString(rt, `
const correct = "aa010fbc1d14c795d86ef98c95479d17";
Expand Down

0 comments on commit fb4d0ce

Please sign in to comment.