28 lines
783 B
Go
28 lines
783 B
Go
// Package auth provides cryptographic core for authentication.
|
|||
|
|
package auth
|
||
|
|
|
||
|
|
import (
|
||
|
|
"crypto/rand"
|
||
|
|
"crypto/sha256"
|
||
|
|
"encoding/hex"
|
||
|
|
"fmt"
|
||
|
|
)
|
||
|
|
|
||
|
|
// GenerateRefreshToken generates a new opaque refresh token (raw) and its SHA256 hash.
|
||
|
|
// The raw token is 32 random bytes hex-encoded; the hash is hex(SHA256(raw)).
|
||
|
|
func GenerateRefreshToken() (raw, hash string, err error) {
|
||
|
|
b := make([]byte, 32)
|
||
|
|
if _, err = rand.Read(b); err != nil {
|
||
|
|
return "", "", fmt.Errorf("auth: generate refresh token: %w", err)
|
||
|
|
}
|
||
|
|
raw = hex.EncodeToString(b)
|
||
|
|
hash = HashRefreshToken(raw)
|
||
|
|
return raw, hash, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// HashRefreshToken returns the SHA256 hash (hex) of the raw refresh token.
|
||
|
|
func HashRefreshToken(raw string) string {
|
||
|
|
sum := sha256.Sum256([]byte(raw))
|
||
|
|
return hex.EncodeToString(sum[:])
|
||
|
|
}
|