Convert a private key (in hex format) into an address.
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)
245569
def make_rsa_keypair(bits):
    
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
        backend=default_backend(),
    )
    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    public_pem = private_key.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    return private_pem, public_pem
1132426
def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key):
    """"""
    decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo())

    try:
        decoded_key = decoded_values[0]
    except IndexError:
        raise ValueError("Invalid public key encoding.")

    return decoded_key["publicKey"].asOctets()
1033780
def to_point
      p = pubkey
      p ||= generate_pubkey(priv_key, compressed: compressed)
      ECDSA::Format::PointOctetString.decode(p.htb, Bitcoin::Secp256k1::GROUP)
    end
1034541
def decrypt(payload, private_key):
        """"""
        cipher = PKCS1_v1_5.new(private_key)
        aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None)
        aes_key = json.loads(aes_key_str.decode("utf-8"))
        key = b64decode(aes_key.get("key"))
        iv = b64decode(aes_key.get("iv"))
        encrypted_magic_envelope = b64decode(payload.get("encrypted_magic_envelope"))
        encrypter = AES.new(key, AES.MODE_CBC, iv)
        content = encrypter.decrypt(encrypted_magic_envelope)
        return etree.fromstring(pkcs7_unpad(content))
176070
def generate_keypair(crypto, seed, password=None):
    
    if crypto in ['eth', 'etc']:
        raise CurrencyNotSupported("Ethereums not yet supported")

    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        # pycrypto etc. must be installed or this will raise ImportError, hence inline import.
        from .bip38 import Bip38EncryptedPrivateKey
        priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)

    return ret
831684
def _get_private_key(cls, private_key_path, private_key_passphrase):
        """"""
        if private_key_path is None or private_key_passphrase is None:
            return None

        with open(private_key_path, 'rb') as key:
            p_key = serialization.load_pem_private_key(
                key.read(),
                password=private_key_passphrase.encode(),
                backend=default_backend())

        return p_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())
116794
def sign_singlesig(privkey_hex, plaintext):
    
    hash_hex = hashlib.sha256(plaintext).hexdigest()
    b64sig = virtualchain.ecdsalib.sign_digest(hash_hex, privkey_hex)
    sighex = binascii.hexlify(base64.b64decode(b64sig))
    pubkey_hex = virtualchain.ecdsalib.ecdsa_private_key(privkey_hex).public_key().to_hex()
    return base64.b64encode(virtualchain.btc_script_serialize([sighex, pubkey_hex]).decode('hex'))
142847
def generate_private_key(key_size=2048):
    """"""
    return cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(
        public_exponent=65537,
        key_size=key_size,
        backend=cryptography.hazmat.backends.default_backend(),
    )
163706
def derivesha256address(self):
        
        pkbin = unhexlify(repr(self._pubkey))
        addressbin = ripemd160(hexlify(hashlib.sha256(pkbin).digest()))
        return Base58(hexlify(addressbin).decode('ascii'))
822382
def asn1_from_ecdsap256_private_key(priv_key, pub_key):
    
    encoded_len = _lib.xtt_asn1_private_key_length()
    encoded = _ffi.new('unsigned char[]', encoded_len)
    rc = _lib.xtt_asn1_from_ecdsap256_private_key(priv_key.native, pub_key.native, encoded, len(encoded))
    if rc == RC.SUCCESS:
        return _ffi.buffer(encoded)[:]
    else:
        raise error_from_code(rc)
1194856
def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key):
    """"""
    algorithm = RsaAlgorithmIdentifier()
    algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID

    pkcs8_key = PKCS8PrivateKey()
    pkcs8_key["version"] = 0
    pkcs8_key["privateKeyAlgorithm"] = algorithm
    pkcs8_key["privateKey"] = pkcs1_key

    return encoder.encode(pkcs8_key)
172269
def hex2ip(hex_ip, invert=False):
    '''
    
    '''
    if len(hex_ip) == 32:  # ipv6
        ip = []
        for i in range(0, 32, 8):
            ip_part = hex_ip[i:i + 8]
            ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)]
            if invert:
                ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part))
            else:
                ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part))
        try:
            address = ipaddress.IPv6Address(":".join(ip))
            if address.ipv4_mapped:
                return str(address.ipv4_mapped)
            else:
                return address.compressed
        except ipaddress.AddressValueError as ex:
            log.error('hex2ip - ipv6 address error: %s', ex)
            return hex_ip

    try:
        hip = int(hex_ip, 16)
    except ValueError:
        return hex_ip
    if invert:
        return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255,
                                        hip >> 16 & 255,
                                        hip >> 8 & 255,
                                        hip & 255)
    return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255,
                                    hip >> 16 & 255,
                                    hip >> 8 & 255,
                                    hip & 255)
617181
def generate_private_key(self):
        
        key_length = self.key_length // 8 + 8
        key = 0

        try:
            key = int.from_bytes(rng(key_length), byteorder='big')
        except:
            key = int(hex(rng(key_length)), base=16)

        self.__private_key = key
461229
def address_to_scripthash(address: str) -> UInt160:
    """"""
    AddressVersion = 23  # fixed at this point
    data = b58decode(address)
    if len(data) != 25:
        raise ValueError('Not correct Address, wrong length.')
    if data[0] != AddressVersion:
        raise ValueError('Not correct Coin Version')

    checksum_data = data[:21]
    checksum = hashlib.sha256(hashlib.sha256(checksum_data).digest()).digest()[:4]
    if checksum != data[21:]:
        raise Exception('Address format error')
    return UInt160(data=data[1:21])
1291443
function pubKeyToAddr(pubKey, pubKeyHash) {
  pubKeyHash = pubKeyHash || zconfig.mainnet.pubKeyHash;

  const hash160 = zcrypto.hash160(Buffer.from(pubKey, 'hex'));
  return bs58check.encode(Buffer.from(pubKeyHash + hash160, 'hex')).toString('hex');
}
624581
def decode_privkey_hex(privkey_hex):
    
    if not isinstance(privkey_hex, (str, unicode)):
        raise ValueError("private key is not a string")

    # force uncompressed
    priv = str(privkey_hex)
    if len(priv) > 64:
        if priv[-2:] != '01':
            raise ValueError("private key does not end in '01'")

        priv = priv[:64]

    pk_i = int(priv, 16)
    return pk_i