How to create a big int with a secure random

huangapple go评论81阅读模式
英文:

How to create a big int with a secure random

问题

我有这段Java代码,我需要在Go中复现。

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

func generateNonce() string {
    nonce, _ := rand.Int(rand.Reader, big.NewInt(1<<130))
    return nonce.Text(32)
}

这是在Go中生成GDS Amadeus SOAP头部4的nonce的方法。希望对你有帮助!

英文:

I have this code in java and I need to reproduce in Go.

String nonce = new BigInteger(130, new SecureRandom()).toString(32);

Is the only way to generate a nonce for GDS amadeus soap header 4.

Thanks

答案1

得分: 8

使用包math/bigcrypto/rand。代码片段如下:

// 最大随机值,一个130位的整数,即2^130 - 1
max := new(big.Int)
max.Exp(big.NewInt(2), big.NewInt(130), nil).Sub(max, big.NewInt(1))

// 在0 - max之间生成具有密码学强度的伪随机数
n, err := rand.Int(rand.Reader, max)
if err != nil {
    // 错误处理
}

// n的32进制字符串表示
nonce := n.Text(32)

可以在Go Playground上找到一个可工作的示例。

英文:

Use package math/big and crypto/rand. The snippet looks like:

//Max random value, a 130-bits integer, i.e 2^130 - 1
max := new(big.Int)
max.Exp(big.NewInt(2), big.NewInt(130), nil).Sub(max, big.NewInt(1))

//Generate cryptographically strong pseudo-random between 0 - max
n, err := rand.Int(rand.Reader, max)
if err != nil {
    //error handling
}

//String representation of n in base 32
nonce := n.Text(32)

A working example can be found at The Go Playground.

答案2

得分: 1

接受的答案是错误的,因为crypto/rand rand.Int函数返回[0,max)范围内的均匀随机值。如果max <= 0,则会引发panic。这是一个不会跳过2^130 - 1值的答案。

// 最大值,一个130位的整数,即2^130 - 1
var max *big.Int = big.NewInt(0).Exp(big.NewInt(2), big.NewInt(130), nil)
// 在[0,max)范围内生成具有密码学强度的伪随机数
n,err := rand.Int(rand.Reader,max)
if err != nil {
// 错误处理
}
fmt.Println(n)

英文:

The accepted answer is wrong because the crypto/rand rand.Int function
> returns a uniform random value in [0, max). It panics if max <= 0.
Here is an answer that doesn't skip the 2^130 - 1 value.

// Max value, a 130-bits integer, i.e 2^130 - 1
var max *big.Int = big.NewInt(0).Exp(big.NewInt(2), big.NewInt(130), nil)
// Generate cryptographically strong pseudo-random between [0, max)
n, err := rand.Int(rand.Reader, max)
if err != nil {
	// error handling
}
fmt.Println(n)

huangapple
  • 本文由 发表于 2017年8月1日 10:43:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/45428126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定