简体   繁体   English

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

[英]multiple-value “crypto/rand”.Int() in single-value context

I am trying to generate a random number using the library crypto/rand.我正在尝试使用库 crypto/rand 生成一个随机数。 The earlier implementation of this function used math/rand, but I need to use crypto/rand.这个 function 的早期实现使用了 math/rand,但我需要使用 crypto/rand。 This is my function below这是我下面的 function

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
}

I am fairly new to this language and hence not able to figure out what should be done.我对这种语言相当陌生,因此无法弄清楚应该做什么。

You can do something like this (although this might not be the best approach)你可以做这样的事情(虽然这可能不是最好的方法)

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM