// MarshalPublicKeyFromPrivateKeyPEM extracts public key from private key
// and returns PEM marshalled key
332322
func MarshalPublicKeyFromPrivateKeyPEM(privateKey crypto.PrivateKey) ([]byte, error) {
	rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey)
	if !ok {
		return nil, trace.BadParameter("expected RSA key")
	}
	rsaPublicKey := rsaPrivateKey.Public()
	derBytes, err := x509.MarshalPKIXPublicKey(rsaPublicKey)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: derBytes}), nil
}
53813
func ConvertECPrivateKeyPEM(inPEM []byte) ([]byte, error) {
	block, _ := pem.Decode(inPEM)
	if block == nil {
		return nil, errors.New("invalid pem bytes")
	}

	var ecPrivKey ecPrivateKey
	if _, err := asn1.Unmarshal(block.Bytes, &ecPrivKey); err != nil {
		return nil, errors.New("invalid ec private key")
	}

	var pkey privateKeyInfo
	pkey.Version = 0
	pkey.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 2)
	pkey.PrivateKeyAlgorithm[0] = oidPublicKeyECDSA
	pkey.PrivateKeyAlgorithm[1] = ecPrivKey.NamedCurveOID

	// remove curve oid from private bytes as it is already mentioned in algorithm
	ecPrivKey.NamedCurveOID = nil

	privatekey, err := asn1.Marshal(ecPrivKey)
	if err != nil {
		return nil, err
	}
	pkey.PrivateKey = privatekey

	der, err := asn1.Marshal(pkey)
	if err != nil {
		return nil, err
	}

	return pem.EncodeToMemory(&pem.Block{
		Type:  "PRIVATE KEY",
		Bytes: der,
	}), nil
}
853375
func readPublicKey(path string) (*rsa.PublicKey, error) {
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	block, _ := pem.Decode(bytes)
	if block == nil {
		return nil, errors.New("failed to decode PEM for key " + path)
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	publicKey, ok := pubInterface.(*rsa.PublicKey)
	if !ok {
		return nil, errors.New("failed to convert public key to rsa.PublicKey")
	}

	return publicKey, nil
}
239330
func AEStoPEM(raw []byte) []byte {
	return pem.EncodeToMemory(&pem.Block{Type: "AES PRIVATE KEY", Bytes: raw})
}
897220
func ParsePublicKeysPEM(keyData []byte) ([]interface{}, error) {
	var block *pem.Block
	keys := []interface{}{}
	for {
		// read the next block
		block, keyData = pem.Decode(keyData)
		if block == nil {
			break
		}

		// test block against parsing functions
		if privateKey, err := parseRSAPrivateKey(block.Bytes); err == nil {
			keys = append(keys, &privateKey.PublicKey)
			continue
		}
		if publicKey, err := parseRSAPublicKey(block.Bytes); err == nil {
			keys = append(keys, publicKey)
			continue
		}
		if privateKey, err := parseECPrivateKey(block.Bytes); err == nil {
			keys = append(keys, &privateKey.PublicKey)
			continue
		}
		if publicKey, err := parseECPublicKey(block.Bytes); 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 any valid RSA or ECDSA public keys")
	}
	return keys, nil
}
312820
func LoadEncryptedPEMPrivKey(reader io.Reader, password []byte) (*rsa.PrivateKey, error) {
	block, err := loadPem(reader)
	if err != nil {
		return nil, err
	}

	decryptedBlock, err := x509.DecryptPEMBlock(block, password)
	if err != nil {
		return nil, err
	}

	return x509.ParsePKCS1PrivateKey(decryptedBlock)
}
1277871
func NewPublicKeysFromFile(user, pemFile, password string) (*PublicKeys, error) {
	bytes, err := ioutil.ReadFile(pemFile)
	if err != nil {
		return nil, err
	}

	return NewPublicKeys(user, bytes, password)
}
717514
func NewKeyFromPrivateKeyPEM(data []byte) (*Key, error) {
	pemBlock, _ := pem.Decode(data)
	if pemBlock == nil {
		return nil, errors.New("cannot find the next PEM formatted block")
	}
	if pemBlock.Type != rsaPrivateKeyPEMBlockType || len(pemBlock.Headers) != 0 {
		return nil, errors.New("unmatched type or headers")
	}

	priv, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
	if err != nil {
		return nil, err
	}

	return NewKey(&priv.PublicKey, priv), nil
}
78324
func RSASignerFromPEM(key []byte) (Signer, error) {
	pkey, err := RSAPrivateKeyFromPEM(key)
	if err != nil {
		return nil, err
	}
	return RSASigner(pkey)
}
1135423
func ImportPublicPEM(in []byte) (pub *PublicKey, err error) {
	p, _ := pem.Decode(in)
	if p == nil || p.Type != "ELLIPTIC CURVE PUBLIC KEY" {
		return nil, ErrInvalidPublicKey
	}

	pub, err = UnmarshalPublic(p.Bytes)
	return
}
469385
func ExtractKeyFromPem(pm string) *btcec.PrivateKey {
	byta := []byte(pm)
	blck, _ := pem.Decode(byta)
	var ecp ecPrivateKey
	asn1.Unmarshal(blck.Bytes, &ecp)
	priv, _ := btcec.PrivKeyFromBytes(btcec.S256(), ecp.PrivateKey)
	return priv
}
820463
func PublicPEM(key *ecdsa.PrivateKey) ([]byte, error) {
	pubBytes, err := x509.MarshalPKIXPublicKey(key.Public())
	if err != nil {
		return nil, err
	}
	pubPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pubBytes,
	})
	return pubPEM, nil
}
760859
func pubkeyFromPrivkey(privkey []byte, compress bool) (pubkey []byte) {
	_, pk := btcec.PrivKeyFromBytes(btcec.S256(), privkey)

	if compress {
		return pk.SerializeCompressed()
	}
	return pk.SerializeUncompressed()
}
980090
func PEMtoPublicKey(raw []byte, pwd []byte) (interface{}, error) {
	if len(raw) == 0 {
		return nil, errors.New("Invalid PEM. It must be different from nil.")
	}
	block, _ := pem.Decode(raw)
	if block == nil {
		return nil, fmt.Errorf("Failed decoding. Block must be different from nil. [% x]", raw)
	}

	// TODO: derive from header the type of the key
	if x509.IsEncryptedPEMBlock(block) {
		if len(pwd) == 0 {
			return nil, errors.New("Encrypted Key. Password must be different from nil")
		}

		decrypted, err := x509.DecryptPEMBlock(block, pwd)
		if err != nil {
			return nil, fmt.Errorf("Failed PEM decryption. [%s]", err)
		}

		key, err := DERToPublicKey(decrypted)
		if err != nil {
			return nil, err
		}
		return key, err
	}

	cert, err := DERToPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return cert, err
}
664299
func MarshalCertificatePEM(cert *x509.Certificate) ([]byte, error) {
	var buf bytes.Buffer

	err := pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return buf.Bytes(), nil
}
533703
func (u *utils) ParsePrivateKeyPEMWithPassword(pemBytes, password []byte) (crypto.Signer, error) {
	block, _ := pem.Decode(pemBytes)
	if block == nil {
		return nil, errors.New("Could not parse PEM")
	}

	if IsPKCS8(block.Bytes) {
		return pkcs8.ParsePrivateKeyPEMWithPassword(pemBytes, password)
	} else if u.fips {
		return nil, ErrFIPSUnsupportedKeyFormat
	}

	return helpers.ParsePrivateKeyPEMWithPassword(pemBytes, password)
}
778536
func (k SigningSecretKey) GetRawPublicKey() *[ed25519.PublicKeySize]byte {
	return (*[ed25519.PublicKeySize]byte)(&k.pub)
}