Initial commit

This commit is contained in:
Alexander Schau 2022-10-30 13:45:03 +00:00
commit af8e2f91e2
5 changed files with 105 additions and 0 deletions

1
README.md Normal file
View File

@ -0,0 +1 @@
# Go Access Token

43
base62.go Normal file
View File

@ -0,0 +1,43 @@
package accessToken
import (
"crypto/rand"
)
func generateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}
func randomBase62String(n int) (string, error) {
const letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes, err := generateRandomBytes(n)
if err != nil {
return "", err
}
for i, b := range bytes {
bytes[i] = letters[b%byte(len(letters))]
}
return string(bytes), nil
}
func EncodeBase62(n int) (string, error) {
letters := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n == 0 {
return "0", nil
}
var base62 string
for n > 0 {
base62 = letters[n%62:n%62+1] + base62
n = n / 62
}
return base62, nil
}

14
crc32.go Normal file
View File

@ -0,0 +1,14 @@
package accessToken
import "hash/crc32"
func getChecksum(text string) (string, error) {
checksum, err := EncodeBase62(int(crc32.ChecksumIEEE([]byte(text))))
if err != nil {
return "", err
}
checksum = "000000" + checksum
checksum = checksum[len(checksum)-6:]
return checksum, nil
}

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.alxs.xyz/alexander/go_access_token
go 1.19

44
main.go Normal file
View File

@ -0,0 +1,44 @@
package accessToken
import (
"errors"
"fmt"
"regexp"
)
func Generate(prefix string, secret string) (string, error) {
if len(prefix) != 3 {
return "", errors.New("prefix is not 3 characters long")
}
randomString, err := randomBase62String(30)
if err != nil {
return "", err
}
firstPart := fmt.Sprintf("%s_%s", prefix, randomString)
checksum, err := getChecksum(firstPart + secret)
if err != nil {
return "", err
}
return firstPart + checksum, nil
}
func Validate(token string, secret string) (bool, error) {
exp := regexp.MustCompile("([abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]{3})_([0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]{30})([0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]{6})")
if !exp.Match([]byte(token)) {
return false, errors.New("wrong token format")
}
checksum, err := getChecksum(token[:len(token)-6] + secret)
if err != nil {
return false, err
}
return token[len(token)-6:] == checksum, nil
}