Skip to content

Instantly share code, notes, and snippets.

@betandr
Created January 16, 2020 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betandr/6f5137d2fd7cad557ed7b82d55c48078 to your computer and use it in GitHub Desktop.
Save betandr/6f5137d2fd7cad557ed7b82d55c48078 to your computer and use it in GitHub Desktop.
Generate keys with crypto/rand
// Do not use package math/rand to generate keys, even throwaway ones.
// Unseeded, the generator is completely predictable. Seeded with
// time.Nanoseconds(), there are just a few bits of entropy. Instead,
// use crypto/rand's Reader, and if you need text, print to hexadecimal
// or base64.
package main
import (
"crypto/rand"
"fmt"
)
func main() {
buf := make([]byte, 16)
_, err := rand.Read(buf)
if err != nil {
panic(err) // out of randomness, should never happen
}
fmt.Printf("%x\n", buf)
// or hex.EncodeToString(buf)
// or base64.StdEncoding.EncodeToString(buf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment