github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/common/keys.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package common 20 21 import ( 22 "crypto/hmac" 23 "crypto/sha256" 24 "encoding/hex" 25 "fmt" 26 27 "github.com/golang-jwt/jwt" 28 ) 29 30 // ComputeHmac256 ... 31 func ComputeHmac256() string { 32 var message = "token" 33 var secret = RandomString(255) 34 35 key := []byte(secret) 36 h := hmac.New(sha256.New, key) 37 h.Write([]byte(message)) 38 39 return hex.EncodeToString(h.Sum(nil)) 40 } 41 42 // ParseHmacToken ... 43 func ParseHmacToken(tokenString string, key []byte) (jwt.MapClaims, error) { 44 45 // Parse takes the token string and a function for looking up the key. The latter is especially 46 // useful if you use multiple keys for your application. The standard is to use 'kid' in the 47 // head of the token to identify which key to use, but the parsed token (head and claims) is provided 48 // to the callback, providing flexibility. 49 token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 50 // Don't forget to validate the alg is what you expect: 51 if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { 52 return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) 53 } 54 55 // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key") 56 return key, nil 57 }) 58 59 if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { 60 return claims, nil 61 } else { 62 return nil, err 63 } 64 }