github.com/Laplace-Game-Development/Laplace-Entangled-Environment@v0.0.3/internal/route/signature.go (about) 1 package route 2 3 import ( 4 "crypto/sha256" 5 "encoding/base64" 6 "errors" 7 "fmt" 8 "log" 9 "time" 10 11 "github.com/Laplace-Game-Development/Laplace-Entangled-Environment/internal/data" 12 "github.com/Laplace-Game-Development/Laplace-Entangled-Environment/internal/util" 13 ) 14 15 // Typical Verification of users for authentication. Used in most 16 // other endpoints as SigVerify in RequestBodyFactories 17 // 18 // Takes the authID, Signature (hash of token and content), and content 19 // to see if the user can indeed make the request (they are who they say 20 // they are). 21 // 22 // returns an error if they are not who they say they are. 23 func SigVerification(authID string, signature string, content *[]byte) error { 24 token, err := data.GetToken(authID) 25 if err != nil { 26 log.Printf("Error in Signature Verification! AuthID:%s\tSignature:%s\nErr: %v\n", authID, signature, err) 27 } 28 29 tokenByte := []byte(token.Token) 30 counterByte := []byte(fmt.Sprintf("%d", token.Uses)) 31 32 if token.Stale.Before(time.Now().UTC()) { 33 return errors.New("Token Is Stale!") 34 } 35 36 contentLen := len(*content) 37 tokenLen := len(tokenByte) 38 counterLen := len(counterByte) 39 40 input := make([]byte, contentLen+tokenLen+counterLen) 41 err = util.Concat(&input, content, 0) 42 if err != nil { 43 return err 44 } 45 46 err = util.Concat(&input, &tokenByte, contentLen) 47 if err != nil { 48 return err 49 } 50 51 err = util.Concat(&input, &counterByte, contentLen+tokenLen) 52 if err != nil { 53 return err 54 } 55 56 checksumByte := sha256.Sum256(input) 57 checksum := base64.RawStdEncoding.EncodeToString(checksumByte[:]) 58 59 if signature == checksum { 60 return data.IncrementTokenUses(authID, token.Uses) 61 } 62 63 return errors.New(fmt.Sprintf("Signature is Incorrect!: %s vs %s", signature, checksum)) 64 } 65 66 func TestHelperGenSig(token *[]byte, content string, counter int) string { 67 counterString := fmt.Sprintf("%d", counter) 68 69 counterByte := []byte(counterString) 70 contentByte := []byte(content) 71 72 contentLen := len(contentByte) 73 tokenLen := len(*token) 74 counterLen := len(counterByte) 75 76 input := make([]byte, contentLen+tokenLen+counterLen) 77 err := util.Concat(&input, &contentByte, 0) 78 if err != nil { 79 return "" 80 } 81 82 err = util.Concat(&input, token, contentLen) 83 if err != nil { 84 return "" 85 } 86 87 err = util.Concat(&input, &counterByte, contentLen+tokenLen) 88 if err != nil { 89 return "" 90 } 91 92 checksumByte := sha256.Sum256(input) 93 checksum := base64.RawStdEncoding.EncodeToString(checksumByte[:]) 94 return checksum 95 }