douyu8187 2016-12-29 15:24
浏览 204
已采纳

PHP的openssl_random_pseudo_bytes替代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.

  • 写回答

2条回答 默认 最新

  • douyiqi9640 2017-02-10 14:55
    关注

    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   = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        letterIdxBits = 6                    // 6 bits to represent a letter index
        letterIdxMask = 1<<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 >= 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏