Skip to content

Instantly share code, notes, and snippets.

@AZ-X
Last active December 12, 2020 11:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AZ-X/1dff5963486807c848eff8ef482f1425 to your computer and use it in GitHub Desktop.
Save AZ-X/1dff5963486807c848eff8ef482f1425 to your computer and use it in GitHub Desktop.
golang-stdlib RNG migration for Windows
_BCryptGenRandom stdFunction
var bcryptdll = []byte("Bcrypt.dll\000")
bcrypt := windowsLoadSystemLib(bcryptdll)
if bcrypt == 0 {
throw("Bcrypt.dll not found")
}
_BCryptGenRandom = windowsFindfunc(bcrypt, []byte("BCryptGenRandom\000"))
//go:nosplit
func getRandomData(r []byte) {
n := 0
const BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002
if stdcall4(_BCryptGenRandom, 0, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)), uintptr(BCRYPT_USE_SYSTEM_PREFERRED_RNG))&0xff != 0 {
n = len(r)
}
extendRandom(r, n)
}
// Copyright 2010 The Go & AZ-X Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Windows cryptographically secure pseudorandom number
// generator.
package rand
import (
"os"
"syscall"
"unsafe"
)
func init() { Reader = &rngReader{} }
type rngReader struct{}
var (
modcng = syscall.NewLazyDLL("Bcrypt.dll")
procBCryptGenRandom = modcng.NewProc("BCryptGenRandom")
)
func bCryptGenRandom(buf *uint8, bytes uint32) (err error) {
const BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002
_, _, e := syscall.Syscall6(procBCryptGenRandom.Addr(), 4, 0, uintptr(unsafe.Pointer(buf)), uintptr(bytes), uintptr(BCRYPT_USE_SYSTEM_PREFERRED_RNG), 0, 0)
switch e {
case 0: err = nil
default: err = e
}
return
}
func (r *rngReader) Read(b []byte) (n int, err error) {
inputLen := uint32(len(b))
if inputLen == 0 {
return 0, nil
}
err = bCryptGenRandom(&b[0], inputLen)
if err != nil {
return 0, os.NewSyscallError("bCryptGenRandom", err)
}
return int(inputLen), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment