当前位置: 首页>>代码示例>>Golang>>正文


Golang jwt-go.ParseRSAPublicKeyFromPEM函数代码示例

本文整理汇总了Golang中github.com/dgrijalva/jwt-go.ParseRSAPublicKeyFromPEM函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseRSAPublicKeyFromPEM函数的具体用法?Golang ParseRSAPublicKeyFromPEM怎么用?Golang ParseRSAPublicKeyFromPEM使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ParseRSAPublicKeyFromPEM函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: VerifyJWTRSA

// Verify a JWT token using an RSA public key
func VerifyJWTRSA(token, publicKey string) (bool, *jwt.Token, error) {

	var parsedToken *jwt.Token

	// parse token
	state, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {

		// ensure signing method is correct
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, errors.New("unknown signing method")
		}

		parsedToken = token

		// verify
		key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKey))
		if err != nil {
			return nil, err
		}

		return key, nil
	})

	if err != nil {
		return false, &jwt.Token{}, err
	}

	if !state.Valid {
		return false, &jwt.Token{}, errors.New("invalid jwt token")
	}

	return true, parsedToken, nil
}
开发者ID:stonedoc,项目名称:stone,代码行数:34,代码来源:crypto.go

示例2: InitTokens

func InitTokens() (err error) {
	signBytes, err := ioutil.ReadFile("config/rsaKey")
	if err != nil {
		log.Error("Error reading private key from file: ", err)
		return
	}

	signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
	if err != nil {
		log.Error("Error parsing private key from file: ", err)
		return
	}

	verifyBytes, err := ioutil.ReadFile("config/pubKey")
	if err != nil {
		log.Error("Error reading public key from file: ", err)
		return
	}

	verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
	if err != nil {
		log.Error("Error parsing public key from file: ", err)
		return
	}
	return
}
开发者ID:4nthem,项目名称:State,代码行数:26,代码来源:auth.go

示例3: GetPublicKeyFromPath

func GetPublicKeyFromPath(path string) *rsa.PublicKey {
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatal(err)
	}
	key, err := jwt.ParseRSAPublicKeyFromPEM(bytes)
	if err != nil {
		log.Fatal(err)
	}
	return key
}
开发者ID:tucobenedicto,项目名称:jsonWebToken,代码行数:11,代码来源:utils.go

示例4: NewToken

// NewToken creates new JWT token for the gien username. It embedds the given
// public key as kontrolKey and signs the token with the private one.
func NewToken(username, private, public string) *jwt.Token {
	tknID := uuid.NewV4()

	hostname, err := os.Hostname()
	if err != nil {
		panic(err)
	}

	if username == "" {
		username = "testuser"
	}

	if testuser := os.Getenv("TESTKEY_USERNAME"); testuser != "" {
		username = testuser
	}

	claims := &kitekey.KiteClaims{
		StandardClaims: jwt.StandardClaims{
			Issuer:   "testuser",
			Subject:  username,
			Audience: hostname,
			IssuedAt: time.Now().UTC().Unix(),
			Id:       tknID.String(),
		},
		KontrolKey: public,
		KontrolURL: "http://localhost:4000/kite",
	}

	token := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims)

	rsaPrivate, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(private))
	if err != nil {
		panic(err)
	}

	token.Raw, err = token.SignedString(rsaPrivate)
	if err != nil {
		panic(err)
	}

	// verify the token
	_, err = jwt.ParseWithClaims(token.Raw, claims, func(*jwt.Token) (interface{}, error) {
		return jwt.ParseRSAPublicKeyFromPEM([]byte(public))
	})

	if err != nil {
		panic(err)
	}

	token.Valid = true
	return token

}
开发者ID:rjeczalik,项目名称:kite,代码行数:55,代码来源:testutil.go

示例5: ReadPublicKey

// ReadPublicKey is a helper function for reading an rsa.PublicKey from a PEM-encoded file
// Reads public keys from both public and private key files
func ReadPublicKey(file string) (*rsa.PublicKey, error) {
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	if privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(data); err == nil {
		return &privateKey.PublicKey, nil
	}

	return jwt.ParseRSAPublicKeyFromPEM(data)
}
开发者ID:40a,项目名称:bootkube,代码行数:14,代码来源:jwt.go

示例6: init

func init() {
	signBytes, err := ioutil.ReadFile(privKeyPath)
	fatal(err)

	signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
	fatal(err)

	verifyBytes, err := ioutil.ReadFile(pubKeyPath)
	fatal(err)

	verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
	fatal(err)
}
开发者ID:gabz75,项目名称:env-auth-go,代码行数:13,代码来源:token.go

示例7: ParseTestPublicKey

func ParseTestPublicKey() interface{} {
	keyBytes, err := ioutil.ReadFile("../test_utils/public.pem")
	if err != nil {
		log.Fatal("Failed to parse public key.", err)
	}

	publicKey, err := jwt.ParseRSAPublicKeyFromPEM(keyBytes)
	if err != nil {
		log.Fatal("Failed to parse public key.", err)
	}

	return publicKey

}
开发者ID:wlan0,项目名称:host-api,代码行数:14,代码来源:utils.go

示例8: ReadPublicKeyFromPEM

// ReadPublicKeyFromPEM is a helper function for reading an rsa.PublicKey or ecdsa.PublicKey from a PEM-encoded byte array.
// Reads public keys from both public and private key files.
func ReadPublicKeyFromPEM(data []byte) (interface{}, error) {
	if privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(data); err == nil {
		return &privateKey.PublicKey, nil
	}
	if publicKey, err := jwt.ParseRSAPublicKeyFromPEM(data); err == nil {
		return publicKey, nil
	}

	if privateKey, err := jwt.ParseECPrivateKeyFromPEM(data); err == nil {
		return &privateKey.PublicKey, nil
	}
	if publicKey, err := jwt.ParseECPublicKeyFromPEM(data); err == nil {
		return publicKey, nil
	}
	return nil, fmt.Errorf("data does not contain a valid RSA or ECDSA key")
}
开发者ID:ncdc,项目名称:kubernetes,代码行数:18,代码来源:jwt.go

示例9: KeyPair

// KeyPair looks up a key pair that was used to sign Kontrol's kite key.
//
// The value is cached on first call of the function.
func (k *Kontrol) KeyPair() (pair *KeyPair, err error) {
	if k.selfKeyPair != nil {
		return k.selfKeyPair, nil
	}

	kiteKey := k.Kite.KiteKey()

	if kiteKey == "" || len(k.lastPublic) == 0 {
		return nil, errNoSelfKeyPair
	}

	keyIndex := -1

	me := new(multiError)

	for i := range k.lastPublic {
		ri := len(k.lastPublic) - i - 1

		keyFn := func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, errors.New("invalid signing method")
			}

			return jwt.ParseRSAPublicKeyFromPEM([]byte(k.lastPublic[ri]))
		}

		if _, err := jwt.ParseWithClaims(kiteKey, &kitekey.KiteClaims{}, keyFn); err != nil {
			me.err = append(me.err, err)
			continue
		}

		keyIndex = ri
		break
	}

	if keyIndex == -1 {
		return nil, fmt.Errorf("no matching self key pair found: %s", me)
	}

	k.selfKeyPair = &KeyPair{
		ID:      k.lastIDs[keyIndex],
		Public:  k.lastPublic[keyIndex],
		Private: k.lastPrivate[keyIndex],
	}

	return k.selfKeyPair, nil
}
开发者ID:rjeczalik,项目名称:kite,代码行数:50,代码来源:kontrol.go

示例10: init

func init() {
	signBytes, err := ioutil.ReadFile(config.Settings.PrivKeyPath)
	if err != nil {
		logger.Log("Reading private Key File "+config.Settings.PrivKeyPath+" failed, Error: "+err.Error(), logger.ERROR)
	}

	signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
	if err != nil {
		logger.Log("Parsing private Key File failed, Error: "+err.Error(), logger.ERROR)
	}

	verifyBytes, err := ioutil.ReadFile(config.Settings.PubKeyPath)
	if err != nil {
		logger.Log("Reading public Key File "+config.Settings.PubKeyPath+" failed, Error: "+err.Error(), logger.ERROR)
	}

	verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
	if err != nil {
		logger.Log("Parsing public Key File failed, Error: "+err.Error(), logger.ERROR)
	}
}
开发者ID:msutter,项目名称:pulp_controller,代码行数:21,代码来源:authentication.go

示例11: generateKeyExtractionFunctionForJTWFlow

func generateKeyExtractionFunctionForJTWFlow(applicationRepo roll.ApplicationRepo) jwt.Keyfunc {
	return func(token *jwt.Token) (interface{}, error) {
		//Check the signing method
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		//The aud claim conveys the intended application the token is used to gain access to.
		clientID := token.Claims["aud"]
		if clientID == nil {
			return nil, errors.New("Foreign token does not include aud claim")
		}

		//Look up the application
		app, err := applicationRepo.SystemRetrieveApplicationByJWTFlowAudience(clientID.(string))
		if err != nil {
			log.Info("Error looking up app for ", clientID, " ", err.Error())
			return nil, err
		}

		if app == nil {
			log.Info("No app definition associated with audience found: ", clientID.(string))
			return nil, errors.New("No app definition associated with aud found")
		}

		//We also check that the token was issued by the entity registered with the application
		issuer := token.Claims["iss"]
		if issuer == nil || issuer != app.JWTFlowIssuer {
			return nil, errors.New("Foreign token issuer not known")
		}

		//Grab the public key from the app definition
		keystring := app.JWTFlowPublicKey

		log.Info("validating with '", keystring, "'")

		//Parse the keystring
		return jwt.ParseRSAPublicKeyFromPEM([]byte(keystring))
	}
}
开发者ID:xtraclabs,项目名称:roll,代码行数:40,代码来源:token.go

示例12: ReadPublicKeysFromPEM

// ReadPublicKeysFromPEM is a helper function for reading an array of rsa.PublicKey or ecdsa.PublicKey from a PEM-encoded byte array.
// Reads public keys from both public and private key files.
func ReadPublicKeysFromPEM(data []byte) ([]interface{}, error) {
	var block *pem.Block
	keys := []interface{}{}
	for {
		// read the next block
		block, data = pem.Decode(data)
		if block == nil {
			break
		}

		// get PEM bytes for just this block
		blockData := pem.EncodeToMemory(block)
		if privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(blockData); err == nil {
			keys = append(keys, &privateKey.PublicKey)
			continue
		}
		if publicKey, err := jwt.ParseRSAPublicKeyFromPEM(blockData); err == nil {
			keys = append(keys, publicKey)
			continue
		}

		if privateKey, err := jwt.ParseECPrivateKeyFromPEM(blockData); err == nil {
			keys = append(keys, &privateKey.PublicKey)
			continue
		}
		if publicKey, err := jwt.ParseECPublicKeyFromPEM(blockData); err == nil {
			keys = append(keys, publicKey)
			continue
		}

		// tolerate non-key PEM blocks for backwards compatibility
		// originally, only the first PEM block was parsed and expected to be a key block
	}

	if len(keys) == 0 {
		return nil, fmt.Errorf("data does not contain a valid RSA or ECDSA key")
	}
	return keys, nil
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:41,代码来源:jwt.go

示例13: updateAuth

func (k *Kite) updateAuth(reg *protocol.RegisterResult) {
	k.configMu.Lock()
	defer k.configMu.Unlock()

	switch {
	case reg.KiteKey != "":
		k.Config.KiteKey = reg.KiteKey

		ex := &kitekey.Extractor{
			Claims: &kitekey.KiteClaims{},
		}

		if _, err := jwt.ParseWithClaims(reg.KiteKey, ex.Claims, ex.Extract); err != nil {
			k.Log.Error("auth update: unable to extract kontrol key: %s", err)

			break
		}

		if ex.Claims.KontrolKey != "" {
			reg.PublicKey = ex.Claims.KontrolKey
		}
	}

	// we also received a new public key (means the old one was invalidated).
	// Use it now.
	if reg.PublicKey != "" {
		k.Config.KontrolKey = reg.PublicKey

		key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(reg.PublicKey))
		if err != nil {
			k.Log.Error("auth update: unable to update kontrol key: %s", err)

			return
		}

		k.kontrolKey = key
	}
}
开发者ID:koding,项目名称:kite,代码行数:38,代码来源:kite.go

示例14: NewAuthResource

func NewAuthResource(privateKeyPath, publicKeyPath string, tokenDuration time.Duration, validator AuthValidator) *AuthResource {
	verifyBytes, err := ioutil.ReadFile(publicKeyPath)
	fatal(err)

	verifyKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
	fatal(err)

	signBytes, err := ioutil.ReadFile(privateKeyPath)
	fatal(err)

	signKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)
	fatal(err)

	if tokenDuration < 1 {
		tokenDuration = DEFAULT_TOKEN_DURATION
	}

	if nil == validator {
		validator = DummyAuthValidator
	}

	return &AuthResource{verifyKey, signKey, tokenDuration, validator}
}
开发者ID:Sennue,项目名称:gogoapi,代码行数:23,代码来源:auth.go

示例15: TestJWTToken

func TestJWTToken(t *testing.T) {
	var err error
	var privateKeyContent, publicKeyContent []byte
	if privateKeyContent, err = ioutil.ReadFile("jwt-test.key"); err != nil {
		t.Fatal(err)
	}
	if publicKeyContent, err = ioutil.ReadFile("jwt-test.pub"); err != nil {
		t.Fatal(err)
	}
	if privateKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateKeyContent); err != nil {
		t.Fatal(err)
	}
	if publicKey, err = jwt.ParseRSAPublicKeyFromPEM(publicKeyContent); err != nil {
		t.Fatal(err)
	}
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims = jwt.MapClaims{
		"PERMISSION": "[email protected]",
		"exp":        time.Now().Add(time.Hour * 72).Unix(),
	}
	ts, err := token.SignedString(privateKey)
	if err != nil {
		t.Fatal(err)
	}
	if token, err = jwt.Parse(ts, func(ts *jwt.Token) (interface{}, error) {
		return publicKey, nil
	}); err != nil {
		t.Fatal(err)
	}
	if token.Valid {
		t.Log(token)
	} else {
		t.Log(token)
		t.Fail()
	}
}
开发者ID:HouzuoGuo,项目名称:tiedot,代码行数:36,代码来源:jwt_test.go


注:本文中的github.com/dgrijalva/jwt-go.ParseRSAPublicKeyFromPEM函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。