1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2025-04-23 12:18:50 +02:00

38 lines
964 B
Go
Raw Normal View History

2019-05-24 17:06:48 +01:00
package encryption
2017-03-27 21:14:38 -04:00
import (
"crypto/hmac"
2017-03-27 21:14:38 -04:00
"crypto/rand"
"encoding/base64"
"golang.org/x/crypto/blake2b"
2017-03-27 21:14:38 -04:00
)
// Nonce generates a random 32-byte slice to be used as a nonce
func Nonce() ([]byte, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
2017-03-27 21:14:38 -04:00
if err != nil {
return nil, err
2017-03-27 21:14:38 -04:00
}
return b, nil
}
// HashNonce returns the BLAKE2b 256-bit hash of a nonce
// NOTE: Error checking (G104) is purposefully skipped:
// - `blake2b.New256` has no error path with a nil signing key
// - `hash.Hash` interface's `Write` has an error signature, but
// `blake2b.digest.Write` does not use it.
/* #nosec G104 */
func HashNonce(nonce []byte) string {
hasher, _ := blake2b.New256(nil)
hasher.Write(nonce)
sum := hasher.Sum(nil)
return base64.RawURLEncoding.EncodeToString(sum)
}
// CheckNonce tests if a nonce matches the hashed version of it
func CheckNonce(nonce []byte, hashed string) bool {
return hmac.Equal([]byte(HashNonce(nonce)), []byte(hashed))
2017-03-27 21:14:38 -04:00
}