go JWT RS256 加解密 "key is of invalid type"

go JWT RS256 加解密 "key is of invalid type"

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

func signed(name string, key interface{}) (string, error) {
	tk := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
		"exp":  fmt.Sprintf("%d", time.Now().Add(time.Minute).Unix()),
		//"exp": time.Now().Add(time.Minute).Unix(),
		"sub":   "1234567890",
		"name":  name,
		"admin": true,
		"iat":   1516239022,
	})
	return tk.SignedString(key)
}

func pares(tokenString string, key interface{}) (interface{}, bool) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		//if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
		//	return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		//}
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return key, nil
	})
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims, true
	} else {
		fmt.Println("======pares:", err)
		return "", false
	}

}

测试代码

import (
	//"crypto/x509"
	//"encoding/base64"
	"io/ioutil"

	//"encoding/pem"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"testing"
)

func TestJWT(t *testing.T) {
	privatekey := `-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAnzyis1ZjfNB0bBgKFMSvvkTtwlvBsaJq7S5wA+kzeVOVpVWw
kWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHcaT92whREFpLv9cj5lTeJSibyr/Mr
m/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIytvHWTxZYEcXLgAXFuUuaS3uF9gEi
NQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0e+lf4s4OxQawWD79J9/5d3Ry0vbV
3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWbV6L11BWkpzGXSW4Hv43qa+GSYOD2
QU68Mb59oSk2OB+BtOL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L382Qx9/THVmbma
3YfRAoGAUxL/Eu5yvMK8SAt/dJK6FedngcM3JEFNplmtLYVLWhkIlNRGDwkg3I5K
y18Ae9n7dHVueyslrb6weq7dTkYDi3iOYRW8HRkIQh06wEdbxt0shTzAJvvCQfrB
jg/3747WSsf/zBTcHihTRBdAv6OmdhV4/dD5YBfLAkLrd+mX7iE=
-----END RSA PRIVATE KEY-----`
	fprikey, err := ioutil.ReadFile("private.txt")
	if err != nil {
		fmt.Println("读取文件错误:", err.Error())
		return
	}
	_ = fprikey
	//bb, err := base64.StdEncoding.DecodeString(privatekey) //解base64
	//if err != nil {
	//	fmt.Println("解base64错误:", err)
	//	t.Fail()
	//	return
	//}
	//_, rest := pem.Decode([]byte(privatekey))

	//priKey, err := x509.ParsePKCS1PrivateKey(bb) //解析私钥
	//if err != nil {
	//	fmt.Println("解析私钥错误:", err)
	//	return
	//}

	priKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(privatekey))
	if err != nil {
		fmt.Println("解析私钥错误:", err)
		return
	}
	fmt.Println("ok")

	_, err = signed("TESTJWT", privatekey) //直接使用私钥字符串签名加密
	if err != nil {
		fmt.Println("1111 signed error:", err.Error())
	}

	str, err := signed("", priKey) //使用解析后的私钥
	if err != nil {
		fmt.Println("2222 signed error:", err.Error())
	} else {
		fmt.Println("signed ok:", str)
	}

	pubkey := `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzyis1ZjfNB0bBgKFMSv
vkTtwlvBsaJq7S5wA+kzeVOVpVWwkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHc
aT92whREFpLv9cj5lTeJSibyr/Mrm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIy
tvHWTxZYEcXLgAXFuUuaS3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0
e+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb
V6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9
MwIDAQAB
-----END PUBLIC KEY-----`

	pb, err := jwt.ParseRSAPublicKeyFromPEM([]byte(pubkey)) //解析公钥
	if err != nil {
		fmt.Println("ParseRSAPublicKeyFromPEM:", err.Error())
		return
	}
	_ = pb

	ret, b := pares(str, pubkey) //直接使用公钥字符串
	if b {
		fmt.Printf("111 pares ok,value:%+v", ret)
	} else {
		fmt.Println("pares error")
	}

	ret, b = pares(str, pb) //使用解析后的公钥
	if b {
		fmt.Printf("222 pares ok,value:%+v", ret)
	} else {
		fmt.Println("pares error")
	}
}

测试结果

D:\>go test
ok
1111 signed error: key is invalid
signed ok: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6dHJ1ZSwiZXhwIjoiMTU3MjQwNzUyNCIsImlhdCI6MTUxNjIzOTAyMiwibmFtZSI6IiIsInN1YiI6IjEyMzQ1Njc4OTAifQ.NvBXpqxHJhTnbfzJGXYPV9EqScJjypt_KLN-apvTgvG-ARqkeqnoQL-Ne41LYc_gZ4GEAiLEUKp5B
z2397wu6VYXiHUMBWW7ti-xli05Nr219hJkmedQtofzxOsGo_xSTTTpQs0wxhVVk6-VclpVE2YiGQxyRzrS8f8430oByDRST8_WLrxerS3_JaYMSk8RVuPN6tNz383BaPDYuSToNcQPFnXpTjMe6eg6V8QpEf8H5MX0jsOA4GT54_LxA0DZmFoo1g_iEEZDnsea9WP6_lHI0xBkoq-5Xto2e7-2KOQvguG9I1iNU
IK0vd5lp1EVhLYMZVYn9MpeUdzCnGWPXA
======pares: key is of invalid type
pares error
222 pares ok,value:map[admin:true exp:1572407524 iat:1.516239022e+09 name: sub:1234567890]PASS

不解析直接使用公钥、私钥字符串签名\验证签名都会提示(key is invalid/key is of invalid type).
解析成正确的公钥、私钥结构再进行签名和验证才不会出现错误。

你可能感兴趣的:(GO)