// LoadPrivateKeyFromPEM loads a private key from a PEM-encoded block.
484856
func LoadPrivateKeyFromPEM(pem_block []byte) (PrivateKey, error) {
	if len(pem_block) == 0 {
		return nil, errors.New("empty pem block")
	}
	bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]),
		C.int(len(pem_block)))
	if bio == nil {
		return nil, errors.New("failed creating bio")
	}
	defer C.BIO_free(bio)

	key := C.PEM_read_bio_PrivateKey(bio, nil, nil, nil)
	if key == nil {
		return nil, errors.New("failed reading private key")
	}

	p := &pKey{key: key}
	runtime.SetFinalizer(p, func(p *pKey) {
		C.X_EVP_PKEY_free(p.key)
	})
	return p, nil
}
191569
func ConvertToECPrivateKeyPEM(inPEM []byte) ([]byte, error) {
	block, _ := pem.Decode(inPEM)
	if block == nil {
		return nil, errors.New("invalid pem bytes")
	}

	var pkey privateKeyInfo
	if _, err := asn1.Unmarshal(block.Bytes, &pkey); err != nil {
		return nil, errors.New("invalid pkcs8 key")
	}

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

	ecPrivKey.NamedCurveOID = pkey.PrivateKeyAlgorithm[1]
	key, err := asn1.Marshal(ecPrivKey)
	if err != nil {
		return nil, err
	}

	return pem.EncodeToMemory(&pem.Block{
		Type:  "EC PRIVATE KEY",
		Bytes: key,
	}), nil
}
580639
func validatePrivatePublicKey(l certKeyLocation) error {
	// Try to load key
	_, _, err := pkiutil.TryLoadPrivatePublicKeyFromDisk(l.pkiDir, l.baseName)
	if err != nil {
		return errors.Wrapf(err, "failure loading key for %s", l.uxName)
	}
	return nil
}
1087837
func firstPrivateKey(s string) (string, error) {
	scanner := bufio.NewScanner(strings.NewReader(s))
	var lines []string
	looking := true
	complete := false
	for scanner.Scan() {
		line := scanner.Text()
		if looking && strings.HasPrefix(line, "-----BEGIN PGP PRIVATE KEY BLOCK-----") {
			looking = false

		}
		if looking {
			continue
		}
		lines = append(lines, line)
		if strings.HasPrefix(line, "-----END PGP PRIVATE KEY BLOCK-----") {
			complete = true
			break
		}
	}
	if err := scanner.Err(); err != nil {
		return "", err
	}
	if looking {
		// never found a private key block
		return "", NoSecretKeyError{}
	}
	if !complete {
		// string ended without the end tag
		return "", errors.New("never found end block line")
	}
	return strings.Join(lines, "\n"), nil
}
518432
func GetPrivateKeyFromCert(cert []byte, cs core.CryptoSuite) (core.Key, error) {

	// get the public key in the right format
	certPubK, err := GetPublicKeyFromCert(cert, cs)
	if err != nil {
		return nil, errors.WithMessage(err, "Failed to import certificate's public key")
	}

	if certPubK == nil || certPubK.SKI() == nil {
		return nil, errors.New("Failed to get SKI")
	}

	// Get the key given the SKI value
	key, err := cs.GetKey(certPubK.SKI())
	if err != nil {
		return nil, errors.WithMessage(err, "Could not find matching key for SKI")
	}

	if key != nil && !key.Private() {
		return nil, errors.Errorf("Found key is not private, SKI: %s", certPubK.SKI())
	}

	return key, nil
}
643174
func LoadTokenVerifyKey() error {
	tokenVerifyKeyPath := os.Getenv(EnvTokenVerifyKey)
	if tokenVerifyKeyPath == "" {
		tokenVerifyKeyPath = TokenVerifyKeyDefault
	}
	tokenVerifyKeyPem, err := ioutil.ReadFile(tokenVerifyKeyPath)
	if err != nil {
		return err
	}
	pemBlock, _ := pem.Decode(tokenVerifyKeyPem)
	if pemBlock.Type != "PUBLIC KEY" {
		return errors.New("Key type was not PUBLIC KEY")
	}
	tokenVerifyKey, err := x509.ParsePKIXPublicKey(pemBlock.Bytes)
	if err != nil {
		return err
	}
	var ok bool
	TokenVerifyKey, ok = tokenVerifyKey.(*rsa.PublicKey)
	if !ok {
		return errors.New(tokenVerifyKeyPath + " could not be loaded")
	}
	return nil
}
962790
func (w *Wallet) ImportPrivateKey(scope waddrmgr.KeyScope, wif *btcutil.WIF,
	bs *waddrmgr.BlockStamp, rescan bool) (string, error) {

	manager, err := w.Manager.FetchScopedKeyManager(scope)
	if err != nil {
		return "", err
	}

	// The starting block for the key is the genesis block unless otherwise
	// specified.
	if bs == nil {
		bs = &waddrmgr.BlockStamp{
			Hash:      *w.chainParams.GenesisHash,
			Height:    0,
			Timestamp: w.chainParams.GenesisBlock.Header.Timestamp,
		}
	} else if bs.Timestamp.IsZero() {
		// Only update the new birthday time from default value if we
		// actually have timestamp info in the header.
		header, err := w.chainClient.GetBlockHeader(&bs.Hash)
		if err == nil {
			bs.Timestamp = header.Timestamp
		}
	}

	// Attempt to import private key into wallet.
	var addr btcutil.Address
	var props *waddrmgr.AccountProperties
	err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
		addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
		maddr, err := manager.ImportPrivateKey(addrmgrNs, wif, bs)
		if err != nil {
			return err
		}
		addr = maddr.Address()
		props, err = manager.AccountProperties(
			addrmgrNs, waddrmgr.ImportedAddrAccount,
		)
		if err != nil {
			return err
		}

		// We'll only update our birthday with the new one if it is
		// before our current one. Otherwise, if we do, we can
		// potentially miss detecting relevant chain events that
		// occurred between them while rescanning.
		birthdayBlock, _, err := w.Manager.BirthdayBlock(addrmgrNs)
		if err != nil {
			return err
		}
		if bs.Height >= birthdayBlock.Height {
			return nil
		}

		err = w.Manager.SetBirthday(addrmgrNs, bs.Timestamp)
		if err != nil {
			return err
		}

		// To ensure this birthday block is correct, we'll mark it as
		// unverified to prompt a sanity check at the next restart to
		// ensure it is correct as it was provided by the caller.
		return w.Manager.SetBirthdayBlock(addrmgrNs, *bs, false)
	})
	if err != nil {
		return "", err
	}

	// Rescan blockchain for transactions with txout scripts paying to the
	// imported address.
	if rescan {
		job := &RescanJob{
			Addrs:      []btcutil.Address{addr},
			OutPoints:  nil,
			BlockStamp: *bs,
		}

		// Submit rescan job and log when the import has completed.
		// Do not block on finishing the rescan.  The rescan success
		// or failure is logged elsewhere, and the channel is not
		// required to be read, so discard the return value.
		_ = w.SubmitRescan(job)
	} else {
		err := w.chainClient.NotifyReceived([]btcutil.Address{addr})
		if err != nil {
			return "", fmt.Errorf("Failed to subscribe for address ntfns for "+
				"address %s: %s", addr.EncodeAddress(), err)
		}
	}

	addrStr := addr.EncodeAddress()
	log.Infof("Imported payment address %s", addrStr)

	w.NtfnServer.notifyAccountProperties(props)

	// Return the payment address string of the imported private key.
	return addrStr, nil
}
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
}
1090947
func RSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
	parsed, err := parsePEM(key)
	if err != nil {
		return nil, err
	}
	var parsedKey crypto.PublicKey
	if parsedKey, err = x509.ParsePKIXPublicKey(parsed); err != nil {
		cert, err := x509.ParseCertificate(parsed)
		if err != nil {
			return nil, ErrNotRSAPublicKey
		}
		parsedKey = cert.PublicKey
	}
	return verifyRSAPublicKey(parsedKey)
}
911671
func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*PrivateKey,
	*PublicKey) {
	x, y := curve.ScalarBaseMult(pk)

	priv := &ecdsa.PrivateKey{
		PublicKey: ecdsa.PublicKey{
			Curve: curve,
			X:     x,
			Y:     y,
		},
		D: new(big.Int).SetBytes(pk),
	}

	return (*PrivateKey)(priv), (*PublicKey)(&priv.PublicKey)
}
1035274
func (p *SetupServerSession) SetupPrivateKeyFromClientPublicKey(key []byte) error {
	key, err := p.session.ComputeKey(key) // S
	if err == nil {
		p.PrivateKey = key
	}

	return err
}
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
}
1096414
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
		return key, nil
	}
	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
		switch key := key.(type) {
		case *rsa.PrivateKey, *ecdsa.PrivateKey:
			return key, nil
		default:
			return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
		}
	}
	if key, err := x509.ParseECPrivateKey(der); err == nil {
		return key, nil
	}

	return nil, errors.New("crypto/tls: failed to parse private key")
}
950175
func GetEncryptedPrivateKey(d Depot, name string, passphrase []byte) (key *pkix.Key, err error) {
	b, err := d.Get(PrivKeyTag(name))
	if err != nil {
		return nil, err
	}
	return pkix.NewKeyFromEncryptedPrivateKeyPEM(b, passphrase)
}
1216663
func (x *XC) ImportPrivateKey(ctx context.Context, buf []byte) error {
	if err := x.secring.Import(buf); err != nil {
		return err
	}
	return x.secring.Save()
}
688260
func LoadMasterKeys(public crypto.PublicKey, private crypto.PrivateKey) {
	mKeyLock.Lock()
	defer mKeyLock.Unlock()
	masterKeys = MasterKeys{public, private}
}
630847
func LoadRSAKeyPair(pub, priv []byte) (public crypto.PublicKey, private crypto.PrivateKey, err error) {
	public, err = RSAPublicKeyFromPEM(pub)
	if err != nil {
		return nil, nil, err
	}

	private, err = RSAPrivateKeyFromPEM(priv)
	if err != nil {
		return nil, nil, err
	}

	return public, private, nil
}