Created
January 9, 2018 09:24
-
-
Save marcusandre/dd4b243dec01acb87e26275cd9192672 to your computer and use it in GitHub Desktop.
Generate a random key with crypto/rand
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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