PHP的openssl_random_pseudo_bytes在Golang中有替代方法吗?

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

PHP's openssl_random_pseudo_bytes Alternative for Golang?

问题

有没有一个与PHP的openssl_random_pseudo_bytes()函数几乎相同的Golang函数?

我需要在Golang中生成伪随机字节串。

英文:

Is there a function for Golang which is or nearly is identicle to PHP's openssl_random_pseudo_bytes() function?

I need this to generate pseudo-random string of bytes in Golang.

答案1

得分: 0

请看一下包"crypto/rand",https://stackoverflow.com/questions/1313223/replace-rand-with-openssl-random-pseudo-bytes?rq=1 和 https://github.com/dgrijalva/jwt-go/blob/master/hmac_example_test.go

func init() {
    // 加载示例密钥数据
    if keyData, e := ioutil.ReadFile("test/hmacTestKey"); e == nil {
        hmacSampleSecret = keyData
    } else {
        panic(e)
    }
}
英文:

Look at package "crypto/rand", https://stackoverflow.com/questions/1313223/replace-rand-with-openssl-random-pseudo-bytes?rq=1 and https://github.com/dgrijalva/jwt-go/blob/master/hmac_example_test.go

func init() {
	// Load sample key data
	if keyData, e := ioutil.ReadFile("test/hmacTestKey"); e == nil {
		hmacSampleSecret = keyData
	} else {
		panic(e)
	}
}

答案2

得分: 0

快速且轻量级的伪随机字节字符串生成器

首先定义一个字节数组,用于生成器(在这种情况下,它应该是字母)
然后决定多少位表示一个字母(这将允许我们逐个获取字母)和包含一个字母所需位数的“模板”
我还存储了我可以从字节数组中获取的最大索引

const (
    letterBytes   = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    letterIdxBits = 6                    // 用于表示字母索引的6位
    letterIdxMask = 1<<letterIdxBits - 1 // 所有1位,与letterIdxBits一样多
    letterIdxMax  = 63 / letterIdxBits   // 在63位中适合的字母索引数量
)

StringRandomizer函数接受一个参数(我想要作为结果得到的字符串的长度)

基本上,这个函数只是一个简单的循环,创建一个具有指定长度和伪随机元素的新字节数组。
直到我填充完结果数组的所有所需元素(没有放入'n'元素),我从letterBytes常量中获取一个随机字母。
如果我最后想要得到的字符串长度大于letterIdxMax,我只需创建一个新的随机63字节序列(src.Int63())并继续循环

func StringRandomizer(n int) string {
    src := rand.NewSource(time.Now().UnixNano())
    b := make([]byte, n)
    // src.Int63()生成63个随机位,足够表示letterIdxMax个字符!
    for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; remain-- {
        if remain == 0 {
            cache, remain = src.Int63(), letterIdxMax
        }
        if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
            b[i] = letterBytes[idx]
            i--
        }
        cache >>= letterIdxBits

    }
    return string(b)
}
英文:

Quick and lightweight pseudo-random string of bytes generator

At first define array of bytes that we want to use for our generator( in this case it shall be letters)
Then decide how many bits represent one letter(it will allow us take letters one by one) and letter "template" that contains amount of bits for one letter
Also I stored maximum index that I can take from my array of bytes

const (
	letterBytes   = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;
	letterIdxBits = 6                    // 6 bits to represent a letter index
	letterIdxMask = 1&lt;&lt;letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
	letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
)

StringRandomizer function gets an argument(length of string that I want to get as result)

Basically, this function just a simple loop that creates a new array of bytes with defined length, and pseudo-random elements.
Until I did not fill in all required elements of result array(did not put 'n' elements), I get one random letter from my letterBytes const.
If length of the string that I want to get at the end more that letterIdxMax, I just create new random sequence of 63 bytes(src.Int63()) and proceed looping

func StringRandomizer(n int) string {
	src := rand.NewSource(time.Now().UnixNano())
	b := make([]byte, n)
	// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
	for i, cache, remain := n-1, src.Int63(), letterIdxMax; i &gt;= 0; remain-- {
		if remain == 0 {
			cache, remain = src.Int63(), letterIdxMax
		}
		if idx := int(cache &amp; letterIdxMask); idx &lt; len(letterBytes) {
			b[i] = letterBytes[idx]
			i--
		}
		cache &gt;&gt;= letterIdxBits

	}
	return string(b)
}

huangapple
  • 本文由 发表于 2016年12月29日 23:24:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/41382570.html
匿名

发表评论

匿名网友

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

确定