Migrated code to Ed25519 certs instead of secret key

This commit is contained in:
Magnus Åhall 2025-05-04 09:54:26 +02:00
parent d3829aa9ec
commit 5856e9af69

26
pkg.go
View file

@ -17,19 +17,28 @@ import (
"github.com/golang-jwt/jwt/v5"
// Standard
"encoding/hex"
"crypto"
"fmt"
"time"
)
type Manager struct {
secret []byte
privKey crypto.PrivateKey
PubKey crypto.PublicKey
ExpireDays int
Initialized bool
}
func NewManager(secret string, expireDays int) (mngr Manager, err error) { // {{{
mngr.secret, err = hex.DecodeString(secret)
func NewManager(private, public string, expireDays int) (mngr Manager, err error) { // {{{
mngr.privKey, err = jwt.ParseEdPrivateKeyFromPEM([]byte(private))
if err != nil {
return
}
mngr.PubKey, err = jwt.ParseEdPublicKeyFromPEM([]byte(public))
if err != nil {
return
}
mngr.ExpireDays = expireDays
mngr.Initialized = true
return
@ -53,10 +62,10 @@ func (mngr *Manager) GenerateToken(data map[string]any) (signedString string) {
data["iat"] = now.Unix()
data["exp"] = now.Add(time.Hour * 24 * time.Duration(mngr.ExpireDays)).Unix()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(data))
token := jwt.NewWithClaims(&jwt.SigningMethodEd25519{}, jwt.MapClaims(data))
// Sign and get the complete encoded token as a string using the secret.
signedString, _ = token.SignedString(mngr.secret)
signedString, _ = token.SignedString(mngr.privKey)
return
} // }}}
func (mngr *Manager) ParseToken(tokenString string) (jwt.MapClaims, error) { // {{{
@ -66,12 +75,11 @@ func (mngr *Manager) ParseToken(tokenString string) (jwt.MapClaims, error) { //
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
if _, ok := token.Method.(*jwt.SigningMethodEd25519); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return mngr.secret, nil
return mngr.PubKey, nil
})
if err != nil {
return nil, err