forked from nirasan/go-oauth-pkce-code-verifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifier.go
64 lines (54 loc) · 1.31 KB
/
verifier.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package go_oauth_pkce_code_verifier
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"math/rand"
"strings"
"time"
)
const (
DefaultLength = 32
MinLength = 32
MaxLength = 96
)
type CodeVerifier struct {
Value string
}
func CreateCodeVerifier() (*CodeVerifier, error) {
return CreateCodeVerifierWithLength(DefaultLength)
}
func CreateCodeVerifierWithLength(length int) (*CodeVerifier, error) {
if length < MinLength || length > MaxLength {
return nil, fmt.Errorf("invalid length: %v", length)
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, length, length)
for i := 0; i < length; i++ {
b[i] = byte(r.Intn(255))
}
return CreateCodeVerifierFromBytes(b)
}
func CreateCodeVerifierFromBytes(b []byte) (*CodeVerifier, error) {
return &CodeVerifier{
Value: encode(b),
}, nil
}
func (v *CodeVerifier) String() string {
return v.Value
}
func (v *CodeVerifier) CodeChallengePlain() string {
return v.Value
}
func (v *CodeVerifier) CodeChallengeS256() string {
h := sha256.New()
h.Write([]byte(v.Value))
return encode(h.Sum(nil))
}
func encode(msg []byte) string {
encoded := base64.StdEncoding.EncodeToString(msg)
encoded = strings.Replace(encoded, "+", "-", -1)
encoded = strings.Replace(encoded, "/", "_", -1)
encoded = strings.Replace(encoded, "=", "", -1)
return encoded
}