GetRandomValues lets you get cryptographically strong random values. As defined by the Web Crypto API's Crypto.getRandomValues() method [specifications]. Do not generate keys using the getRandomValues method. Use the generateKey method instead. The array given as the parameter is filled with rando
(typedArray sobek.Value)
| 36 | // |
| 37 | // [specification]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues |
| 38 | func (c *Crypto) GetRandomValues(typedArray sobek.Value) sobek.Value { |
| 39 | acceptedTypes := []JSType{ |
| 40 | Int8ArrayConstructor, |
| 41 | Uint8ArrayConstructor, |
| 42 | Uint8ClampedArrayConstructor, |
| 43 | Int16ArrayConstructor, |
| 44 | Uint16ArrayConstructor, |
| 45 | Int32ArrayConstructor, |
| 46 | Uint32ArrayConstructor, |
| 47 | } |
| 48 | |
| 49 | // 1. |
| 50 | if !IsInstanceOf(c.vu.Runtime(), typedArray, acceptedTypes...) { |
| 51 | common.Throw(c.vu.Runtime(), NewError(TypeMismatchError, "typedArray parameter isn't a TypedArray instance")) |
| 52 | } |
| 53 | |
| 54 | // 2. |
| 55 | // Obtain the length of the typed array, and throw a QuotaExceededError if |
| 56 | // it's too big, as specified in the [spec's] 10.2.1.2 paragraph. |
| 57 | // [spec]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues |
| 58 | obj := typedArray.ToObject(c.vu.Runtime()) |
| 59 | objLength, ok := obj.Get("length").ToNumber().Export().(int64) |
| 60 | if !ok { |
| 61 | common.Throw(c.vu.Runtime(), NewError(TypeMismatchError, "typedArray parameter isn't a TypedArray instance")) |
| 62 | } |
| 63 | |
| 64 | if objLength > maxRandomValuesLength { |
| 65 | common.Throw( |
| 66 | c.vu.Runtime(), |
| 67 | NewError( |
| 68 | QuotaExceededError, |
| 69 | fmt.Sprintf("typedArray parameter is too big; maximum length is %d", maxRandomValuesLength), |
| 70 | ), |
| 71 | ) |
| 72 | } |
| 73 | |
| 74 | // 3. |
| 75 | // Create a buffer of a matching size and fill |
| 76 | // it with random values. |
| 77 | // |
| 78 | // We use crypto/rand.Read() here as it will use /dev/urandom or |
| 79 | // an equivalent on Unix-like systems, and CryptGenRandom() |
| 80 | // on Windows. This is the recommended way to generate random |
| 81 | // by the specification. |
| 82 | randomValues := make([]byte, objLength) |
| 83 | _, err := rand.Read(randomValues) |
| 84 | if err != nil { |
| 85 | common.Throw(c.vu.Runtime(), err) |
| 86 | } |
| 87 | |
| 88 | for i := range objLength { |
| 89 | err := obj.Set(strconv.FormatInt(i, 10), randomValues[i]) |
| 90 | if err != nil { |
| 91 | common.Throw(c.vu.Runtime(), err) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // Although the input array has been modified in place, |