Skip to content

Instantly share code, notes, and snippets.

@marcusandre
Created January 9, 2018 09:24
Show Gist options
  • Save marcusandre/dd4b243dec01acb87e26275cd9192672 to your computer and use it in GitHub Desktop.
Save marcusandre/dd4b243dec01acb87e26275cd9192672 to your computer and use it in GitHub Desktop.
Generate a random key with crypto/rand
// Example to generate a random key with crypto/rand.
// It's useful to use it for example to prevent request forgery by comparing it
// inside requests.
package main
import (
"crypto/rand"
"fmt"
"log"
)
func main() {
key, err := generateKey()
if err != nil {
log.Fatal(err)
}
fmt.Println(key)
}
func generateKey() (string, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", b), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment