@@ -17,8 +17,13 @@ limitations under the License.
1717package mw
1818
1919import (
20+ "crypto"
21+ "crypto/ed25519"
22+ "crypto/x509"
23+ "encoding/pem"
2024 "errors"
2125 "fmt"
26+ "sync"
2227 "time"
2328
2429 "github.com/golang-jwt/jwt/v4"
@@ -108,17 +113,17 @@ func CheckToken(token string) (int64, string, error) {
108113 return - 1 , "" , errno .AuthError .WithMessage ("cannot handle claims" )
109114 }
110115
111- secret , err := jwt . ParseEdPublicKeyFromPEM ([] byte ( constants . PublicKey ) )
116+ publicKey , err := getPublicKey ( )
112117 if err != nil {
113- return - 1 , "" , errno .AuthError .WithMessage (fmt .Sprintf ("parse public key failed, err: %v" , err ))
118+ return - 1 , "" , errno .AuthError .WithMessage (fmt .Sprintf ("get public key failed, err: %v" , err ))
114119 }
115120
116121 // 使用正确的密钥再次解析 token
117122 response , err := jwt .ParseWithClaims (token , & Claims {}, func (token * jwt.Token ) (interface {}, error ) {
118123 if _ , ok := token .Method .(* jwt.SigningMethodEd25519 ); ! ok {
119124 return nil , errno .AuthError .WithMessage (fmt .Sprintf ("unexpected signing method: %v" , token .Header ["alg" ]))
120125 }
121- return secret , nil
126+ return publicKey , nil
122127 })
123128 // 验证 token 是否有效
124129 if err != nil {
@@ -145,3 +150,22 @@ func checkError(err error, tokenType int64) error {
145150 }
146151 return errno .AuthError .WithMessage (err .Error ())
147152}
153+
154+ var getPublicKey = sync .OnceValues (func () (crypto.PublicKey , error ) {
155+ block , _ := pem .Decode ([]byte (config .Server .Secret ))
156+ if block == nil {
157+ return nil , fmt .Errorf ("failed to decode PEM block" )
158+ }
159+
160+ keyAny , err := x509 .ParsePKCS8PrivateKey (block .Bytes )
161+ if err != nil {
162+ return nil , fmt .Errorf ("failed to parse PKCS8 private key: %w" , err )
163+ }
164+
165+ privateKey , ok := keyAny .(ed25519.PrivateKey )
166+ if ! ok {
167+ return nil , fmt .Errorf ("key is not ed25519 private key" )
168+ }
169+
170+ return privateKey .Public (), nil
171+ })
0 commit comments