doudi1979 2018-10-17 19:50
浏览 201
已采纳

在“ crypto / rand”成功之前生成随机字符串是个好主意吗?

Is it a good idea to generate a secure random hex string until the process succeeds?

All examples I've come across show that if rand.Read returns error, we should panic, os.Exit(1) or return empty string and the error.

I need my program to continue to function in case of such errors and wait until a random string is generated. Is it a good idea to loop until the string is generated, any pitfalls with that?

import "crypto/rand"

func RandomHex() string {
    var buf [16]byte
    for {
        _, err := rand.Read(buf[:])
        if err == nil {
            break
        }
    }
    return hex.EncodeToString(buf[:])
}
  • 写回答

2条回答 默认 最新

  • doulei3488 2018-10-17 21:55
    关注

    Is it a good idea to loop until the string is generated,

    That depends. Probably yes.

    any pitfalls with that?

    You discard the random bytes read on error. And this in a tight loop. This may drain you entropy source (depending on the OS) faster than it can be filled.

    Instead of an unbound infinite loop: Break after n rounds and give up. Graceful degradation or stopping is best: If your program is stuck in an endless loop it is also not "continue"ing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?