fix basic tests.

This commit is contained in:
Jae Kwon
2014-10-04 19:16:49 -07:00
parent 11a79f11e0
commit 1ae9ecd2a9
18 changed files with 443 additions and 270 deletions

View File

@ -4,6 +4,7 @@ import (
crand "crypto/rand"
"encoding/hex"
"math/rand"
"time"
)
const (
@ -12,7 +13,7 @@ const (
func init() {
// Seed math/rand with "secure" int64
b := RandBytes(8)
b := CRandBytes(8)
var seed uint64
for i := 0; i < 8; i++ {
seed |= uint64(b[i])
@ -22,7 +23,6 @@ func init() {
}
// Constructs an alphanumeric string of given length.
// Not crypto safe
func RandStr(length int) string {
chars := []byte{}
MAIN_LOOP:
@ -46,8 +46,67 @@ MAIN_LOOP:
return string(chars)
}
// Crypto safe
func RandBytes(numBytes int) []byte {
func RandUInt16() uint16 {
return uint16(rand.Uint32() & (1<<16 - 1))
}
func RandUInt32() uint32 {
return rand.Uint32()
}
func RandUInt64() uint64 {
return uint64(rand.Uint32())<<32 + uint64(rand.Uint32())
}
// Distributed pseudo-exponentially to test for various cases
func RandUInt16Exp() uint16 {
bits := rand.Uint32() % 16
if bits == 0 {
return 0
}
n := uint16(1 << (bits - 1))
n += uint16(rand.Int31()) & ((1 << (bits - 1)) - 1)
return n
}
// Distributed pseudo-exponentially to test for various cases
func RandUInt32Exp() uint32 {
bits := rand.Uint32() % 32
if bits == 0 {
return 0
}
n := uint32(1 << (bits - 1))
n += uint32(rand.Int31()) & ((1 << (bits - 1)) - 1)
return n
}
// Distributed pseudo-exponentially to test for various cases
func RandUInt64Exp() uint64 {
bits := rand.Uint32() % 64
if bits == 0 {
return 0
}
n := uint64(1 << (bits - 1))
n += uint64(rand.Int63()) & ((1 << (bits - 1)) - 1)
return n
}
func RandTime() time.Time {
return time.Unix(int64(RandUInt64Exp()), 0)
}
func RandBytes(n int) []byte {
bs := make([]byte, n)
for i := 0; i < n; i++ {
bs[i] = byte(rand.Intn(256))
}
return bs
}
//-----------------------------------------------------------------------------
// CRand* methods are crypto safe.
func CRandBytes(numBytes int) []byte {
b := make([]byte, numBytes)
_, err := crand.Read(b)
if err != nil {
@ -56,8 +115,7 @@ func RandBytes(numBytes int) []byte {
return b
}
// Crypto safe
// RandHex(24) gives 96 bits of randomness, strong enough for most purposes.
func RandHex(numDigits int) string {
return hex.EncodeToString(RandBytes(numDigits / 2))
func CRandHex(numDigits int) string {
return hex.EncodeToString(CRandBytes(numDigits / 2))
}