Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/rand/rand_js.go

Documentation: crypto/rand

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build js && wasm
     6  // +build js,wasm
     7  
     8  package rand
     9  
    10  import "syscall/js"
    11  
    12  func init() {
    13  	Reader = &reader{}
    14  }
    15  
    16  var jsCrypto = js.Global().Get("crypto")
    17  var uint8Array = js.Global().Get("Uint8Array")
    18  
    19  // reader implements a pseudorandom generator
    20  // using JavaScript crypto.getRandomValues method.
    21  // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues.
    22  type reader struct{}
    23  
    24  func (r *reader) Read(b []byte) (int, error) {
    25  	a := uint8Array.New(len(b))
    26  	jsCrypto.Call("getRandomValues", a)
    27  	js.CopyBytesToGo(b, a)
    28  	return len(b), nil
    29  }
    30  

View as plain text