go - 单值上下文中的多值“crypto/rand” .Int()

标签 go cryptography

我正在尝试使用库crypto / rand生成一个随机数。该函数的较早实现使用math / rand,但是我需要使用crypto / rand。这是我下面的功能

func GenerateNum() (num string) {
num = fmt.Sprintf("02:fc:%02x:%02x:%02x:%02x", rand.Int(rand.Reader, big.NewInt(256)),
rand.Int(rand.Reader, big.NewInt(256)), rand.Int(rand.Reader, big.NewInt(256)),
rand.Int(rand.Reader, big.NewInt(256))
)
return
}

我对这种语言还很陌生,因此无法弄清楚应该怎么做。

最佳答案

您可以执行类似的操作(尽管这可能不是最佳方法)

package main

import (
    "crypto/rand"
    "fmt"
    "log"
    "math/big"
)

func cryptoRandSecure() *big.Int {
    nBig, err := rand.Int(rand.Reader, big.NewInt(256))
    if err != nil {
        log.Println(err)
    }
    return nBig
}

func GenerateNum() (num string) {
    n1 := cryptoRandSecure()
    n2 := cryptoRandSecure()
    n3 := cryptoRandSecure()
    n4 := cryptoRandSecure()
    num = fmt.Sprintf("02:fc:%02x:%02x:%02x:%02x", n1, n2, n3, n4)
    return
}

func main() {
    num := GenerateNum()
    fmt.Println(num)
}

关于go - 单值上下文中的多值“crypto/rand” .Int(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61625935/

相关文章:

java - 如何以编程方式生成自签名证书?

security - 公开暴露盐是否可以接受?

java - JAVA 中的 PKCS5 或基于密码的加密 (PBE)

java - Java 中的椭圆曲线私钥长度

api - 在 Go 中通过 HTTP 接收二进制数据

algorithm - 如何在golang中按字符a对字符串数组进行排序

go - 使用 jsonpb 解码自定义类型

multithreading - Go 服务器在发送 INT 信号后挂起

json - 将 JSON 对象中的两个值连接到 Go 中的 map[string]bool

cryptography - FPGA逻辑单元数量与性能的关系