Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add crypto.randomBytes #922

Merged
merged 7 commits into from
Feb 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
na-- marked this conversation as resolved.
Show resolved Hide resolved
_, 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