forked from awnumar/memguard
-
Notifications
You must be signed in to change notification settings - Fork 1
/
auxiliary.go
38 lines (33 loc) · 1 KB
/
auxiliary.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package memguard
import (
"crypto/rand"
"unsafe"
)
// Round a length to a multiple of the system page size.
func roundToPageSize(length int) int {
return (length + (pageSize - 1)) & (^(pageSize - 1))
}
// Get a slice that describes all memory related to a LockedBuffer.
func getAllMemory(b *LockedBuffer) []byte {
bufLen, roundedBufLen := len(b.Buffer), roundToPageSize(len(b.Buffer)+32)
memAddr := uintptr(unsafe.Pointer(&b.Buffer[0])) - uintptr((roundedBufLen-bufLen)+pageSize)
memLen := (pageSize * 2) + roundedBufLen
return getBytes(memAddr, memLen)
}
// Convert a pointer and length to a byte slice that describes that memory.
func getBytes(ptr uintptr, len int) []byte {
var sl = struct {
addr uintptr
len int
cap int
}{ptr, len, len}
return *(*[]byte)(unsafe.Pointer(&sl))
}
// Cryptographically Secure Pseudo-Random Number Generator.
func csprng(n int) []byte {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panic("memguard._csprng(): could not get random bytes")
}
return b
}