From 162bff99b2eca4716c9617415dfe6825292552d1 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Wed, 16 Jul 2014 17:23:13 -0700 Subject: [PATCH] addrbook key is more secure --- common/random.go | 32 +++++++++++++++++++++++++++++++- p2p/addrbook.go | 2 +- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/common/random.go b/common/random.go index 6e92d96df..d68ac6da5 100644 --- a/common/random.go +++ b/common/random.go @@ -1,6 +1,8 @@ package common import ( + crand "crypto/rand" + "encoding/hex" "math/rand" ) @@ -8,7 +10,19 @@ const ( strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 characters ) -// Construts an alphanumeric string of given length. +func init() { + // Seed math/rand with "secure" int64 + b := RandBytes(8) + var seed uint64 + for i := 0; i < 8; i++ { + seed |= uint64(b[i]) + seed <<= 8 + } + rand.Seed(int64(seed)) +} + +// Constructs an alphanumeric string of given length. +// Not crypto safe func RandStr(length int) string { chars := []byte{} MAIN_LOOP: @@ -31,3 +45,19 @@ MAIN_LOOP: return string(chars) } + +// Crypto safe +func RandBytes(numBytes int) []byte { + b := make([]byte, numBytes) + _, err := crand.Read(b) + if err != nil { + panic(err) + } + 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)) +} diff --git a/p2p/addrbook.go b/p2p/addrbook.go index 9e9c845c7..584da1173 100644 --- a/p2p/addrbook.go +++ b/p2p/addrbook.go @@ -106,7 +106,7 @@ func NewAddrBook(filePath string) *AddrBook { // When modifying this, don't forget to update loadFromFile() func (a *AddrBook) init() { - a.key = RandStr(12) + a.key = RandHex(24) // 24/2 * 8 = 96 bits // addr -> ka index a.addrLookup = make(map[string]*knownAddress) // New addr buckets