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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度