Golang Cryptographic Shuffle

时间:2016-02-04 14:28:21

标签: go cryptography shuffle

我正在尝试在Go中使用crypto / rand而不是math / rand来实现字符串shuffle函数。 Fisher-Yates Shuffle需要随机整数,因此我尝试实现该功能,而不必使用依赖crypto/rand Intmath/big。以下是迄今为止我提出的最好的方法,但有更好的方法吗?事实上,我找不到现有的例子,这让我想知道为什么没有人这样做是有充分理由的!

read_terms

3 个答案:

答案 0 :(得分:4)

Go math/rand库具有良好的工具,可以从Source生成随机数字基元。

// A Source represents a source of uniformly-distributed 
// pseudo-random int64 values in the range [0, 1<<63).

type Source interface {
    Int63() int64
    Seed(seed int64)
}

NewSource(seed int64)返回内置的确定性PRNG,但New(source Source)将允许任何满足Source接口的内容。

以下是Source支持的crypto/rand示例。

type CryptoRandSource struct{}

func NewCryptoRandSource() CryptoRandSource {
    return CryptoRandSource{}
}

func (_ CryptoRandSource) Int63() int64 {
    var b [8]byte
    rand.Read(b[:])
    // mask off sign bit to ensure positive number
    return int64(binary.LittleEndian.Uint64(b[:]) & (1<<63 - 1))
}

func (_ CryptoRandSource) Seed(_ int64) {}

你可以像这样使用它:

r := rand.New(NewCryptoRandSource())

for i := 0; i < 10; i++ {
    fmt.Println(r.Int())
}

math/rand库具有正确实施的Intn()方法,可确保统一分发。

func (r *Rand) Intn(n int) int {
    if n <= 0 {
        panic("invalid argument to Intn")
    }
    if n <= 1<<31-1 {
        return int(r.Int31n(int32(n)))
    }
    return int(r.Int63n(int64(n)))
}

func (r *Rand) Int31n(n int32) int32 {
    if n <= 0 {
        panic("invalid argument to Int31n")
    }
    if n&(n-1) == 0 { // n is power of two, can mask
        return r.Int31() & (n - 1)
    }
    max := int32((1 << 31) - 1 - (1<<31)%uint32(n))
    v := r.Int31()
    for v > max {
        v = r.Int31()
    }
    return v % n
}

func (r *Rand) Int63n(n int64) int64 {
    if n <= 0 {
        panic("invalid argument to Int63n")
    }
    if n&(n-1) == 0 { // n is power of two, can mask
        return r.Int63() & (n - 1)
    }
    max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
    v := r.Int63()
    for v > max {
        v = r.Int63()
    }
    return v % n
}

加密哈希函数也可以包装为Source,用于替代随机方式。

答案 1 :(得分:0)

来自n % max的数字未统一分配。例如,

package main

import (
    "fmt"
    "math"
)

func main() {
    max := 7
    size := math.MaxUint8
    count := make([]int, size)
    for i := 0; i < size; i++ {
        count[i%max]++
    }
    fmt.Println(count[:max])
}

输出:

[37 37 37 36 36 36 36]

答案 2 :(得分:-1)

基于收到的评论,我想我可以通过添加一个uniformInt函数来改进我的问题中的示例,填充uint32而不是uint16并删除指向切片的指针。

package main

import "crypto/rand"
import "fmt"
import "encoding/binary"

func randomInt() int {
        var n uint32
        binary.Read(rand.Reader, binary.LittleEndian, &n)
        return int(n)
}

func uniformInt(max int) (r int) {
        divisor := 4294967295 / max // Max Uint32
        for {
                r = randomInt() / divisor
                if r <= max {
                        break
                }
        }
        return
}

func shuffle(slice []string) {
        for i := range slice {
                j := uniformInt(i + 1)
                slice[i], slice[j] = slice[j], slice[i]
        }
}

func main() {
        slice := []string{"a", "b", "c", "d", "e", "f", "h", "i", "j", "k"}
        shuffle(slice)
        fmt.Println(slice)
}