// RSAKey returns the corresponding public key for the issuer of the token.
// It is called by jwt-go package when validating the signature in the token.
519036
func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) {
	k.verifyOnce.Do(k.verifyInit)

	kontrolKey := k.KontrolKey()

	if kontrolKey == nil {
		panic("kontrol key is not set in config")
	}

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

	claims, ok := token.Claims.(*kitekey.KiteClaims)
	if !ok {
		return nil, errors.New("token does not have valid claims")
	}

	if claims.Issuer != k.Config.KontrolUser {
		return nil, fmt.Errorf("issuer is not trusted: %s", claims.Issuer)
	}

	return kontrolKey, nil
}
1019434
func SignJWT(jwt ClientJWT, pk jose.JsonWebKey) (string, error) {
	signer, err := jose.NewSigner(jose.RS512, &pk)
	if err != nil {
		return "", errors.Annotate(err, "Couldn't create JWT Signer")
	}
	json, err := json.Marshal(jwt)
	if err != nil {
		return "", errors.Annotate(err, "Couldn't marshal the JWT")
	}
	jws, err := signer.Sign(json)
	if err != nil {
		return "", errors.Annotate(err, "Couldn't sign the JWT")
	}
	return jws.CompactSerialize()
}
1258535
func RSAVerifierFromPEM(key []byte) (Verifier, error) {
	pkey, err := RSAPublicKeyFromPEM(key)
	if err != nil {
		return nil, err
	}
	return RSAVerifier(pkey)
}
1302324
func PublicKeyToDER(publicKey interface{}) ([]byte, error) {
	if publicKey == nil {
		return nil, errors.New("Invalid public key. It must be different from nil.")
	}

	switch k := publicKey.(type) {
	case *ecdsa.PublicKey:
		if k == nil {
			return nil, errors.New("Invalid ecdsa public key. It must be different from nil.")
		}
		PubASN1, err := x509.MarshalPKIXPublicKey(k)
		if err != nil {
			return nil, err
		}

		return PubASN1, nil

	case *rsa.PublicKey:
		if k == nil {
			return nil, errors.New("Invalid rsa public key. It must be different from nil.")
		}
		PubASN1, err := x509.MarshalPKIXPublicKey(k)
		if err != nil {
			return nil, err
		}

		return PubASN1, nil

	default:
		return nil, errors.New("Invalid key type. It must be *ecdsa.PublicKey or *rsa.PublicKey")
	}
}
221251
func SignRS256(r *rsa.PrivateKey, data []byte) ([]byte, error) {
	h := sha256.New()
	h.Write(data)
	d := h.Sum(nil)
	return rsa.SignPKCS1v15(rand.Reader, r, crypto.SHA256, d)
}
371438
func builtinJWTVerify(a ast.Value, b ast.Value, verify func(publicKey interface{}, digest []byte, signature []byte) error) (ast.Value, error) {
	// Decode the JSON Web Token
	token, err := decodeJWT(a)
	if err != nil {
		return nil, err
	}

	// Process PEM encoded certificate input
	astCertificate, err := builtins.StringOperand(b, 2)
	if err != nil {
		return nil, err
	}
	key, err := getKeyFromCert(string(astCertificate))
	if err != nil {
		return nil, err
	}

	signature, err := token.decodeSignature()
	if err != nil {
		return nil, err
	}

	// Validate the JWT signature
	err = verify(key,
		getInputSHA([]byte(token.header+"."+token.payload)),
		[]byte(signature))

	if err != nil {
		return ast.Boolean(false), nil
	}
	return ast.Boolean(true), nil
}
137247
func LoadTokenSignKey() error {
	tokenSignKeyPath := os.Getenv(EnvTokenSignKey)
	if tokenSignKeyPath == "" {
		tokenSignKeyPath = TokenSignKeyDefault
	}
	tokenSignKeyPem, err := ioutil.ReadFile(tokenSignKeyPath)
	if err != nil {
		return err
	}
	pemBlock, _ := pem.Decode(tokenSignKeyPem)
	if pemBlock.Type != "RSA PRIVATE KEY" {
		return errors.New("Key type was not RSA PRIVATE KEY")
	}
	tokenSignKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
	if err != nil {
		return err
	}
	TokenSignKey = tokenSignKey
	return nil
}
1307328
func PEMFromRSAPublicKey(key crypto.PublicKey, headers map[string]string) ([]byte, error) {
	pkey, err := verifyRSAPublicKey(key)
	if err != nil {
		return nil, err
	}
	marshalled, err := x509.MarshalPKIXPublicKey(pkey)
	if err != nil {
		return []byte{}, err
	}
	block := pem.Block{
		Type:    "PUBLIC KEY",
		Headers: headers,
		Bytes:   marshalled,
	}
	bytes := pem.EncodeToMemory(&block)
	return bytes, nil
}
133151
func ParsePrivateKeyDER(keyDER []byte) (key crypto.Signer, err error) {
	generalKey, err := x509.ParsePKCS8PrivateKey(keyDER)
	if err != nil {
		generalKey, err = x509.ParsePKCS1PrivateKey(keyDER)
		if err != nil {
			generalKey, err = x509.ParseECPrivateKey(keyDER)
			if err != nil {
				generalKey, err = ParseEd25519PrivateKey(keyDER)
				if err != nil {
					// We don't include the actual error into
					// the final error. The reason might be
					// we don't want to leak any info about
					// the private key.
					return nil, cferr.New(cferr.PrivateKeyError,
						cferr.ParseFailed)
				}
			}
		}
	}

	switch generalKey.(type) {
	case *rsa.PrivateKey:
		return generalKey.(*rsa.PrivateKey), nil
	case *ecdsa.PrivateKey:
		return generalKey.(*ecdsa.PrivateKey), nil
	case ed25519.PrivateKey:
		return generalKey.(ed25519.PrivateKey), nil
	}

	// should never reach here
	return nil, cferr.New(cferr.PrivateKeyError, cferr.ParseFailed)
}
1363128
func ParseSigner(pemValue string) (crypto.Signer, error) {
	// The _ result below is not an error but the remaining PEM bytes.
	block, _ := pem.Decode([]byte(pemValue))
	if block == nil {
		return nil, fmt.Errorf("no PEM-encoded data found")
	}

	switch block.Type {
	case "EC PRIVATE KEY":
		return x509.ParseECPrivateKey(block.Bytes)

	case "RSA PRIVATE KEY":
		return x509.ParsePKCS1PrivateKey(block.Bytes)

	case "PRIVATE KEY":
		signer, err := x509.ParsePKCS8PrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		pk, ok := signer.(crypto.Signer)
		if !ok {
			return nil, fmt.Errorf("private key is not a valid format")
		}

		return pk, nil

	default:
		return nil, fmt.Errorf("unknown PEM block type for signing key: %s", block.Type)
	}
}
1038768
func builtinJWTVerifyRS256(a ast.Value, b ast.Value) (ast.Value, error) {
	return builtinJWTVerifyRSA(a, b, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error {
		return rsa.VerifyPKCS1v15(
			publicKey,
			crypto.SHA256,
			digest,
			signature)
	})
}
1178337
func rsaGenerate(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, label string, modulusLen, pubExponent uint) (*rsa.PublicKey, error) {
	keyID := make([]byte, 4)
	_, err := rand.Read(keyID)
	if err != nil {
		return nil, err
	}
	log.Printf("Generating RSA key with %d bit modulus and public exponent %d and ID %x\n", modulusLen, pubExponent, keyID)
	args := rsaArgs(label, modulusLen, pubExponent, keyID)
	pub, priv, err := ctx.GenerateKeyPair(session, args.mechanism, args.publicAttrs, args.privateAttrs)
	if err != nil {
		return nil, err
	}
	log.Println("Key generated")
	log.Println("Extracting public key")
	pk, err := rsaPub(ctx, session, pub, modulusLen, pubExponent)
	if err != nil {
		return nil, err
	}
	log.Println("Extracted public key")
	log.Println("Verifying public key")
	err = rsaVerify(ctx, session, priv, pk)
	if err != nil {
		return nil, err
	}
	return pk, nil
}
844434
func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
	var publicKeyBytes []byte
	var publicKeyAlgorithm pkix.AlgorithmIdentifier
	var err error

	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
		return nil, err
	}

	pkix := pkixPublicKey{
		Algo: publicKeyAlgorithm,
		BitString: asn1.BitString{
			Bytes:     publicKeyBytes,
			BitLength: 8 * len(publicKeyBytes),
		},
	}

	ret, _ := asn1.Marshal(pkix)
	return ret, nil
}
601614
func decodeKey(publicKey interface{}) (string, int) {
	switch publicKey.(type) {
	case *dsa.PublicKey:
		return "DSA", publicKey.(*dsa.PublicKey).P.BitLen()
	case *ecdsa.PublicKey:
		return "ECDSA", publicKey.(*ecdsa.PublicKey).Curve.Params().BitSize
	case *rsa.PublicKey:
		return "RSA", publicKey.(*rsa.PublicKey).N.BitLen()
	default:
		return "", 0
	}
}
412502
func (key *Key) PublicKey() *Key {
	keyBytes := key.Key

	if key.IsPrivate {
		keyBytes = publicKeyForPrivateKey(keyBytes)
	}

	return &Key{
		Version:     PublicWalletVersion,
		Key:         keyBytes,
		Depth:       key.Depth,
		ChildNumber: key.ChildNumber,
		FingerPrint: key.FingerPrint,
		ChainCode:   key.ChainCode,
		IsPrivate:   false,
	}
}
407920
func CryptoPublicKey(publicKey []byte) (crypto.PublicKey, error) {
	// reuse the same RSA keys for SSH and TLS keys
	pubKey, _, _, _, err := ssh.ParseAuthorizedKey(publicKey)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	cryptoPubKey, ok := pubKey.(ssh.CryptoPublicKey)
	if !ok {
		return nil, trace.BadParameter("expected ssh.CryptoPublicKey, got %T", pubKey)
	}
	return cryptoPubKey.CryptoPublicKey(), nil
}
463258
func (f *jwtFilter) getKey(token *jwt.Token) (interface{}, error) {
	return f.publicKey, nil
}