2014-12-07 15:41:24 +00:00
|
|
|
// Copyright (C) 2014 The Syncthing Authors.
|
|
|
|
//
|
2015-03-07 20:36:35 +00:00
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
|
|
|
// You can obtain one at http://mozilla.org/MPL/2.0/.
|
2014-12-07 15:41:24 +00:00
|
|
|
|
2016-03-25 07:35:18 +00:00
|
|
|
package util
|
2014-12-07 15:41:24 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/md5"
|
|
|
|
cryptoRand "crypto/rand"
|
|
|
|
"encoding/binary"
|
2014-12-08 18:36:08 +00:00
|
|
|
"io"
|
2014-12-07 15:41:24 +00:00
|
|
|
mathRand "math/rand"
|
|
|
|
)
|
|
|
|
|
|
|
|
// randomCharset contains the characters that can make up a randomString().
|
|
|
|
const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
|
|
|
|
|
2016-03-25 07:35:18 +00:00
|
|
|
// RandomString returns a string of random characters (taken from
|
2014-12-07 15:41:24 +00:00
|
|
|
// randomCharset) of the specified length.
|
2016-03-25 07:35:18 +00:00
|
|
|
func RandomString(l int) string {
|
2014-12-07 15:41:24 +00:00
|
|
|
bs := make([]byte, l)
|
|
|
|
for i := range bs {
|
|
|
|
bs[i] = randomCharset[mathRand.Intn(len(randomCharset))]
|
|
|
|
}
|
|
|
|
return string(bs)
|
|
|
|
}
|
|
|
|
|
2016-03-25 07:35:18 +00:00
|
|
|
// RandomInt64 returns a strongly random int64, slowly
|
|
|
|
func RandomInt64() int64 {
|
2014-12-07 15:41:24 +00:00
|
|
|
var bs [8]byte
|
2014-12-08 18:40:38 +00:00
|
|
|
_, err := io.ReadFull(cryptoRand.Reader, bs[:])
|
|
|
|
if err != nil {
|
|
|
|
panic("randomness failure: " + err.Error())
|
2014-12-07 15:41:24 +00:00
|
|
|
}
|
2016-03-25 07:35:18 +00:00
|
|
|
return SeedFromBytes(bs[:])
|
2014-12-07 15:41:24 +00:00
|
|
|
}
|
|
|
|
|
2016-03-25 07:35:18 +00:00
|
|
|
// SeedFromBytes calculates a weak 64 bit hash from the given byte slice,
|
2014-12-07 15:41:24 +00:00
|
|
|
// suitable for use a predictable random seed.
|
2016-03-25 07:35:18 +00:00
|
|
|
func SeedFromBytes(bs []byte) int64 {
|
2014-12-07 15:41:24 +00:00
|
|
|
h := md5.New()
|
|
|
|
h.Write(bs)
|
|
|
|
s := h.Sum(nil)
|
|
|
|
// The MD5 hash of the byte slice is 16 bytes long. We interpret it as two
|
|
|
|
// uint64s and XOR them together.
|
|
|
|
return int64(binary.BigEndian.Uint64(s[0:]) ^ binary.BigEndian.Uint64(s[8:]))
|
|
|
|
}
|