Get the private key from a WIF key

        Args:
            wif (str): The wif key

        Returns:
            bytes: The private key
960670
def PrivateKeyFromWIF(wif):
        
        if wif is None or len(wif) is not 52:
            raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif)))

        data = base58.b58decode(wif)

        length = len(data)

        if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01:
            raise ValueError("Invalid format!")

        checksum = Crypto.Hash256(data[0:34])[0:4]

        if checksum != data[34:]:
            raise ValueError("Invalid WIF Checksum!")

        return data[1:33]
415663
async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
        
        if self.public_key is None:
            raise ValueError('Public key not provided during initialisation, cannot encrypt key encrypting key')

        random_bytes = os.urandom(32)

        ciphertext = await self._loop.run_in_executor(
            None, lambda: (self.public_key.encrypt(random_bytes, padding.PKCS1v15())))

        return random_bytes, {}, base64.b64encode(ciphertext).decode()
1157441
def get_extended_key(self):
        
        network_hex_chars = hexlify(
            chr_py2(self.network.SECRET_KEY))
        return ensure_bytes(network_hex_chars + self.get_key())
1121745
async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
        
        if self.private_key is None:
            raise ValueError('Private key not provided during initialisation, cannot decrypt key encrypting key')

        plaintext = await self._loop.run_in_executor(None, lambda: (self.private_key.decrypt(key, padding.PKCS1v15())))

        return plaintext
23304
func (priv *PrivateKey) FromWIF(wif string) (err error) {
	/* See https://en.bitcoin.it/wiki/Wallet_import_format */

	/* Base58 Check Decode the WIF string */
	ver, priv_bytes, err := b58checkdecode(wif)
	if err != nil {
		return err
	}

	/* Check that the version byte is 0x80 */
	if ver != 0x80 {
		return fmt.Errorf("Invalid WIF version 0x%02x, expected 0x80.", ver)
	}

	/* If the private key bytes length is 33, check that suffix byte is 0x01 (for compression) and strip it off */
	if len(priv_bytes) == 33 {
		if priv_bytes[len(priv_bytes)-1] != 0x01 {
			return fmt.Errorf("Invalid private key, unknown suffix byte 0x%02x.", priv_bytes[len(priv_bytes)-1])
		}
		priv_bytes = priv_bytes[0:32]
	}

	/* Convert from bytes to a private key */
	err = priv.FromBytes(priv_bytes)
	if err != nil {
		return err
	}

	/* Derive public key from private key */
	priv.derive()

	return nil
}
816995
def compressedpubkey(self):
        
        secret = unhexlify(repr(self._wif))
        order = ecdsa.SigningKey.from_string(
            secret, curve=ecdsa.SECP256k1).curve.generator.order()
        p = ecdsa.SigningKey.from_string(
            secret, curve=ecdsa.SECP256k1).verifying_key.pubkey.point
        x_str = ecdsa.util.number_to_string(p.x(), order)
        y_str = ecdsa.util.number_to_string(p.y(), order)
        compressed = hexlify(
            chr(2 + (p.y() & 1)).encode('ascii') + x_str
        ).decode('ascii')
        uncompressed = hexlify(
            chr(4).encode('ascii') + x_str + y_str).decode(
            'ascii')
        return [compressed, uncompressed]
229178
def export_private_key(self, password=None):
		

		if self.__private_key is None:
			raise ValueError('Unable to call this method. Private key must be set')

		if password is not None:
			if isinstance(password, str) is True:
				password = password.encode()
			return self.__private_key.private_bytes(
				encoding=serialization.Encoding.PEM,
				format=serialization.PrivateFormat.PKCS8,
				encryption_algorithm=serialization.BestAvailableEncryption(password)
			)
		return self.__private_key.private_bytes(
			encoding=serialization.Encoding.PEM,
			format=serialization.PrivateFormat.TraditionalOpenSSL,
			encryption_algorithm=serialization.NoEncryption()
		)
40970
def from_ewif_hex(cls: Type[SigningKeyType], ewif_hex: str, password: str) -> SigningKeyType:
        
        ewif_bytes = Base58Encoder.decode(ewif_hex)
        if len(ewif_bytes) != 39:
            raise Exception("Error: the size of EWIF is invalid")

        # extract data
        fi = ewif_bytes[0:1]
        checksum_from_ewif = ewif_bytes[-2:]
        ewif_no_checksum = ewif_bytes[0:-2]
        salt = ewif_bytes[1:5]
        encryptedhalf1 = ewif_bytes[5:21]
        encryptedhalf2 = ewif_bytes[21:37]

        # check format flag
        if fi != b"\x02":
            raise Exception("Error: bad format version, not EWIF")

        # checksum control
        checksum = libnacl.crypto_hash_sha256(libnacl.crypto_hash_sha256(ewif_no_checksum))[0:2]
        if checksum_from_ewif != checksum:
            raise Exception("Error: bad checksum of the EWIF")

        # SCRYPT
        password_bytes = password.encode("utf-8")
        scrypt_seed = scrypt(password_bytes, salt, 16384, 8, 8, 64)
        derivedhalf1 = scrypt_seed[0:32]
        derivedhalf2 = scrypt_seed[32:64]

        # AES
        aes = pyaes.AESModeOfOperationECB(derivedhalf2)
        decryptedhalf1 = aes.decrypt(encryptedhalf1)
        decryptedhalf2 = aes.decrypt(encryptedhalf2)

        # XOR
        seed1 = xor_bytes(decryptedhalf1, derivedhalf1[0:16])
        seed2 = xor_bytes(decryptedhalf2, derivedhalf1[16:32])
        seed = bytes(seed1 + seed2)

        # Password Control
        signer = SigningKey(seed)
        salt_from_seed = libnacl.crypto_hash_sha256(
            libnacl.crypto_hash_sha256(
                Base58Encoder.decode(signer.pubkey)))[0:4]
        if salt_from_seed != salt:
            raise Exception("Error: bad Password of EWIF address")

        return cls(seed)
337218
def private_key_to_address(self, pk):
        
        pub = privtopub(pk)
        pub_byte, priv_byte = get_magic_bytes(self.crypto)

        if priv_byte >= 128:
            priv_byte -= 128 #pybitcointools bug

        return pubtoaddr(pub, pub_byte)
105246
def CreateKey(self, private_key=None):
        
        if private_key is None:
            private_key = bytes(Random.get_random_bytes(32))

        key = KeyPair(priv_key=private_key)
        self._keys[key.PublicKeyHash.ToBytes()] = key
        return key
240293
public static function PrivateKeyFromWif($privateWif) {
//        var private_wif = new ByteBuffer(base58.decode(_private_wif));
//        var version = private_wif.readUInt8(0);
//        assert.equal(0x80, version, `Expected version ${0x80}, instead got ${version}`);
//        // checksum includes the version
//        var private_key = private_wif.slice(0, -4);
//        var checksum = private_wif.slice(-4);
//        var new_checksum = hash.sha256(private_key);
//        new_checksum = hash.sha256(new_checksum);
//        new_checksum = new_checksum.slice(0, 4);
//        if (checksum.toString() !== new_checksum.toString())
//            throw new Error('Invalid WIF key (checksum miss-match)')
//
//        private_key = private_key.slice(1);
//return PrivateKey.fromBuffer(private_key);

        //checking wif version
        $base58 = new Base58();
        $wifBuffer = new ByteBuffer();
        $wifBuffer->write($base58->decode($privateWif));
        $version = $wifBuffer->readInt8(0);
        if ($version !== 128) {
            //        assert.equal(0x80, version, `Expected version ${0x80}, instead got ${version}`);
            throw new \Exception('Expected version 128, instead got ' . $version);
        }

        //checking WIF checksum
        $private_key = $wifBuffer->read(0, $wifBuffer->length() - 4);
        $checksum = $wifBuffer->read($wifBuffer->length() - 4, 4);
        $new_checksum = hash('sha256', $private_key, true);
        $new_checksum = hash('sha256', $new_checksum, true);
        $new_checksum = substr($new_checksum, 0, 4);
        if ($new_checksum !== $checksum) {
            throw new \Exception('Invalid WIF key (checksum miss-match)');
        }

        //getting private_key
//        $private_key = substr(strrev($wifBuffer->read(0, $wifBuffer->length())), 1, -4);
        $private_key = substr($private_key, 1);
//        if (32 !== buf.length) {
//            console.log(`WARN: Expecting 32 bytes, instead got ${buf.length}, stack trace:`, new Error().stack);
//        }
        $length = strlen($private_key);
        if ($length !== 32) {
            throw new \Exception('Expecting 32 bytes for private_key, instead got ' . $length);
        }

        return $private_key;
    }
40944
def __set_private_key(self, pk):
		
		self.__private_key = pk
		self.__public_key = pk.public_key()
896237
def wif(self, is_compressed=None):
        
        secret_exponent = self.secret_exponent()
        if secret_exponent is None:
            return None
        if is_compressed is None:
            is_compressed = self.is_compressed()
        blob = to_bytes_32(secret_exponent)
        if is_compressed:
            blob += b'\01'
        return self._network.wif_for_blob(blob)
876665
def secret_key_bytes(self):
        ''' 

        '''
        if not hasattr(self, '_secret_key_bytes'):
            key = self.secret_key()
            if key is None:
                self._secret_key_bytes = None
            else:
                self._secret_key_bytes = codecs.encode(key, "utf-8")
        return self._secret_key_bytes
391171
def ed25519_private_key_to_string(key):
    
    return base64.b64encode(key.private_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PrivateFormat.Raw,
        encryption_algorithm=serialization.NoEncryption()
    ), None).decode('utf-8')
1235175
def export_wif(self) -> str:
        
        data = b''.join([b'\x80', self.__private_key, b'\01'])
        checksum = Digest.hash256(data[0:34])
        wif = base58.b58encode(b''.join([data, checksum[0:4]]))
        return wif.decode('ascii')
1039835
def serialize_private_key_to_pem(private_key, passphrase_bytes=None):
    
    return private_key.private_bytes(
        encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
        format=cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=cryptography.hazmat.primitives.serialization.BestAvailableEncryption(
            passphrase_bytes
        )
        if passphrase_bytes is not None
        else cryptography.hazmat.primitives.serialization.NoEncryption(),
    )