Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Random 使用crypto/rand生成带有rand.Perm的置换_Random_Go - Fatal编程技术网

Random 使用crypto/rand生成带有rand.Perm的置换

Random 使用crypto/rand生成带有rand.Perm的置换,random,go,Random,Go,Go有两个随机数软件包: crypto/rand,它提供了一种获取随机字节的方法 math/rand,它有一个很好的整型算法 我想使用math/rand中的Perm算法,但提供高质量的随机数 由于两个rand包是同一标准库的一部分,因此应该有一种方法将它们组合在一起,以便crypto/rand提供一个好的随机数源,供math/rand.Perm生成置换 以下是我为连接这两个包而编写的代码: package main import ( cryptoRand "crypto/rand"

Go有两个随机数软件包:

  • crypto/rand
    ,它提供了一种获取随机字节的方法
  • math/rand
    ,它有一个很好的整型算法
我想使用
math/rand
中的
Perm
算法,但提供高质量的随机数

由于两个
rand
包是同一标准库的一部分,因此应该有一种方法将它们组合在一起,以便
crypto/rand
提供一个好的随机数源,供
math/rand.Perm
生成置换

以下是我为连接这两个包而编写的代码:

package main

import (
    cryptoRand "crypto/rand"
    "encoding/binary"
    "fmt"
    mathRand "math/rand"
)

type cryptoSource struct{}

func (s cryptoSource) Int63() int64 {
    bytes := make([]byte, 8, 8)
    cryptoRand.Read(bytes)
    return int64(binary.BigEndian.Uint64(bytes) >> 1)
}

func (s cryptoSource) Seed(seed int64) {
    panic("seed")
}

func main() {
    rnd := mathRand.New(&cryptoSource{})
    perm := rnd.Perm(52)
    fmt.Println(perm)
}

这个代码有效。理想情况下,我不想自己定义
cryptoSource
类型,而只是将两个
rand
包粘在一起,以便它们一起工作。那么,在什么地方有这种
加密源类型的预定义版本吗?

这基本上就是您需要做的。对于
math/rand
的常见用法,通常不需要加密安全的随机性源,因此没有提供适配器。通过直接在结构中分配缓冲区空间,而不是在每次调用时分配新的片,可以使实现稍微更高效

type cryptoSource struct {
    buf [8]byte
}

func (s *cryptoSource) Int63() int64 {
    cryptoRand.Read(s.buf[:])
    return int64(binary.BigEndian.Uint64(s.buf[:]) & (1<<63 - 1))
}

math/rand
用于伪随机数,但如果您需要用于加密算法、密码生成、会话ID等的真实随机数,则必须使用
crypto/rand
,不清楚您的问题是什么?@YandryPozo,math/rand可以作为任意随机源的有用包装,以获得特定的数字输出。
type cryptoSource [8]byte

func (s *cryptoSource) Int63() int64 {
    cryptoRand.Read(s[:])
    return int64(binary.BigEndian.Uint64(s[:]) & (1<<63 - 1))
}