git.iko.soy/typeable/oauth2-proxy
on ea261ca help sign in
37 lines 964 B history raw
1package encryption
3import (
4 "crypto/hmac"
5 "crypto/rand"
6 "encoding/base64"
8 "golang.org/x/crypto/blake2b"
9)
11// Nonce generates a random 32-byte slice to be used as a nonce
12func Nonce() ([]byte, error) {
13 b := make([]byte, 32)
14 _, err := rand.Read(b)
15 if err != nil {
16 return nil, err
17 }
18 return b, nil
21// HashNonce returns the BLAKE2b 256-bit hash of a nonce
22// NOTE: Error checking (G104) is purposefully skipped:
23// - `blake2b.New256` has no error path with a nil signing key
24// - `hash.Hash` interface's `Write` has an error signature, but
25// `blake2b.digest.Write` does not use it.
26/* #nosec G104 */
27func HashNonce(nonce []byte) string {
28 hasher, _ := blake2b.New256(nil)
29 hasher.Write(nonce)
30 sum := hasher.Sum(nil)
31 return base64.RawURLEncoding.EncodeToString(sum)
34// CheckNonce tests if a nonce matches the hashed version of it
35func CheckNonce(nonce []byte, hashed string) bool {
36 return hmac.Equal([]byte(HashNonce(nonce)), []byte(hashed))