2019-05-24 17:06:48 +01:00
|
|
|
package encryption
|
2017-03-27 21:14:38 -04:00
|
|
|
|
|
|
|
import (
|
2021-04-21 02:33:27 -07:00
|
|
|
"crypto/hmac"
|
2017-03-27 21:14:38 -04:00
|
|
|
"crypto/rand"
|
2025-03-25 15:12:37 -05:00
|
|
|
"crypto/sha256"
|
2021-04-21 02:33:27 -07:00
|
|
|
"encoding/base64"
|
2017-03-27 21:14:38 -04:00
|
|
|
)
|
|
|
|
|
2022-03-13 06:08:33 -04:00
|
|
|
// Nonce generates a random n-byte slice
|
|
|
|
func Nonce(length int) ([]byte, error) {
|
|
|
|
b := make([]byte, length)
|
2021-04-21 02:33:27 -07:00
|
|
|
_, err := rand.Read(b)
|
2017-03-27 21:14:38 -04:00
|
|
|
if err != nil {
|
2021-04-21 02:33:27 -07:00
|
|
|
return nil, err
|
2017-03-27 21:14:38 -04:00
|
|
|
}
|
2021-04-21 02:33:27 -07:00
|
|
|
return b, nil
|
|
|
|
}
|
|
|
|
|
2025-03-25 15:12:37 -05:00
|
|
|
// HashNonce returns the SHA256 hash of a nonce
|
2021-04-21 02:33:27 -07:00
|
|
|
func HashNonce(nonce []byte) string {
|
2025-03-25 15:12:37 -05:00
|
|
|
if nonce == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
hasher := sha256.New()
|
2021-04-21 02:33:27 -07:00
|
|
|
hasher.Write(nonce)
|
|
|
|
sum := hasher.Sum(nil)
|
2025-03-25 15:12:37 -05:00
|
|
|
|
2021-04-21 02:33:27 -07:00
|
|
|
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
|
|
|
}
|