Beispiel #1
0
    def private_key_to_wif(private_key):

        decode_hex = codecs.getdecoder("hex_codec")
        encode_hex = codecs.getencoder("hex_codec")

        output = Qtum.validate_private_key_for_wif(private_key)
        extended_private_key = output
        #print(output)

        output = decode_hex(output)[0]
        output = sha256(output).digest()
        #print(encode_hex(output)[0])

        output = sha256(output).digest()
        #print(encode_hex(output)[0])

        output = encode_hex(output)[0]
        checksum = output[:8]
        output = extended_private_key + checksum.decode()
        #print(output)

        output = decode_hex(output)[0]
        #print('my_raw:' + str(output))
        output = base58check.b58encode(output)
        #print(output)

        return output.decode()
def pub_to_addr(pub_key):
    """Returns an encoded base58 address for the given public key."""
    sha = sha256(pub_key)
    ripe = ripemd160(sha)
    #add mainnet code
    ripe = b"\x00" + ripe
    return base58check.b58encode(ripe + sha_check_sum(ripe))
Beispiel #3
0
    def to_wif(self, compressed=True):
        """Returns key in WIFC or WIF string

        |  Pseudocode:
        |      network_prefix = (1 byte version number)
        |      data = network_prefix + (32 bytes number/key) [ + 0x01 if compressed ]
        |      data_hash = SHA-256( SHA-256( data ) )
        |      checksum = (first 4 bytes of data_hash)
        |      wif = Base58CheckEncode( data + checksum )
        """

        # add network prefix to the key
        data = NETWORK_WIF_PREFIXES[get_network()] + self.to_bytes()

        if compressed == True:
            data += b'\x01'

        # double hash and get the first 4 bytes for checksum
        data_hash = hashlib.sha256(hashlib.sha256(data).digest()).digest()
        checksum = data_hash[0:4]

        # suffix the key bytes with the checksum and encode to base58check
        wif = b58encode(data + checksum)

        return wif.decode('utf-8')
def priv_to_WIF(priv_key):
    """Returns the WIF key (encoded in base 58) given a private key."""
    #adds mainnet locator
    priv_key = b"\x80" + priv_key
    #runs two rounds of sha256 to get checksum
    checksum = sha_check_sum(priv_key)
    return base58check.b58encode(priv_key + checksum)
Beispiel #5
0
    def from_xpub(
        xpub: str,
        xpub_type: Optional[XpubType] = None,
        path: Optional[str] = None,
    ) -> 'HDKey':
        """
        Instantiate an HDKey from an xpub. Populates all possible fields
        Args:
            xpub (str): the xpub
            path (str): the path if it's known. useful for calling derive_path
        Returns:
            (HDKey): the key object

        May raise:
        - XPUBError if there is a problem with decoding the xpub
        """
        xpub_bytes = b58decode(xpub)
        if len(xpub_bytes) < 78:
            raise XPUBError(f'Given XPUB {xpub} is too small')

        try:
            pubkey = PublicKey(xpub_bytes[45:78])
        except ValueError as e:
            raise XPUBError(str(e)) from e

        result = _parse_prefix(xpub_bytes[0:4])
        if not result.is_public:
            raise XPUBError('Given xpub is an extended private key')

        if result.network != 'mainnet':
            raise XPUBError('Given xpub is not for the bitcoin mainnet')

        hint = result.hint
        if xpub_type is not None and xpub_type.matches_prefix(
                xpub[0:4]) is False:
            # the given type does not match the prefix, re-encode with correct pref
            new_xpub = bytearray()
            new_xpub.extend(xpub_type.prefix_bytes())
            new_xpub.extend(xpub_bytes[4:])
            new_xpub_bytes = new_xpub
            hint = xpub_type.prefix()
            xpub = b58encode(bytes(new_xpub_bytes)).decode('ascii')

        return HDKey(
            path=path,
            network=result.network,
            depth=xpub_bytes[4],
            parent_fingerprint=xpub_bytes[5:9],
            index=int.from_bytes(xpub_bytes[9:13], byteorder='big'),
            parent=None,
            chain_code=xpub_bytes[13:45],
            fingerprint=hash160(pubkey.format(COMPRESSED_PUBKEY))[:4],
            xpriv=None,
            xpub=xpub,
            privkey=None,
            pubkey=pubkey,
            hint=hint,
        )
Beispiel #6
0
def seckey_to_wif(seckey: str, testnet=True):
    if testnet:
        version = 'ef'
    else:
        version = '80'
    seckey = version + seckey
    checksum = create_hash_from_string(create_hash_from_string(seckey))[0:8]
    cat = seckey + checksum
    return base58check.b58encode(bytes.fromhex(cat)).decode()
Beispiel #7
0
def getNewAddress(pubkey):
    # Version prefix for SMLY
    version_prefix = b'\x19'
    pubkeybytes = bytes.fromhex(pubkey)
    sha256 = hashlib.sha256(pubkeybytes).digest()
    ripemd160 = hashlib.new('ripemd160')
    ripemd160.update(sha256)
    payload = ripemd160.digest()
    checksum = hashlib.sha256(hashlib.sha256(version_prefix + payload).digest()).digest()[0:4]
    return base58check.b58encode(version_prefix + payload + checksum)
Beispiel #8
0
def hex_to_p2pkh(pubkey: str, testnet=True) -> str:
    #bytes_key=bytes.fromhex(pubkey)
    if testnet:
        version = '6f'  # 111
    else:
        version = '00'
    key_hash = version + hash160(pubkey)
    checksum = create_hash_from_string(create_hash_from_string(key_hash))[0:8]
    cat = key_hash + checksum
    return base58check.b58encode(bytes.fromhex(cat)).decode()
Beispiel #9
0
def scriptpubkey_to_p2sh_address(data: bytes) -> BTCAddress:
    """Return a P2SH address given a scriptpubkey

    P2SH: OP_HASH160 <scriptHash> OP_EQUAL
    """
    if data[0:1] != OpCodes.op_hash160 or data[-1:] != OpCodes.op_equal:
        raise EncodingError(f'Invalid P2SH scriptpubkey: {data.hex()}')

    prefixed_hash = bytes.fromhex('05') + data[2:22]  # 20 byte pubkey hash
    checksum = hashlib.sha256(hashlib.sha256(prefixed_hash).digest()).digest()
    address = base58check.b58encode(prefixed_hash + checksum[:4])
    return BTCAddress(address.decode('ascii'))
Beispiel #10
0
def pubkey_to_base58_address(data: bytes) -> BTCAddress:
    """
    Bitcoin pubkey to base58 address

    Source:
    https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses#How_to_create_Bitcoin_Address
    https://hackernoon.com/how-to-generate-bitcoin-addresses-technical-address-generation-explanation-rus3z9e

    May raise:
    - ValueError, TypeError due to b58encode
    """
    prefixed_hash, checksum = _calculate_hash160_and_checksum(b'\x00', data)
    return BTCAddress(base58check.b58encode(prefixed_hash + checksum[:4]).decode('ascii'))
Beispiel #11
0
    def private_key_to_wif(private_key, mainnet=True):
        output = Bip32NetworkKeys._validate_private_key_for_wif(private_key, mainnet)
        extended_private_key = output

        output = decode_hex(output)[0]
        checksum = sha256(sha256(output).digest()).hexdigest()[:8]

        output = extended_private_key + checksum

        output = decode_hex(output)[0]
        output = base58check.b58encode(output)

        return output.decode()
Beispiel #12
0
    def __init__(self, entropy):  # todo: init from private key
        entropy = entropy.encode()

        self.decode_hex = codecs.getdecoder("hex_codec")
        self.encode_hex = codecs.getencoder("hex_codec")

        key = BIP32Key.fromEntropy(entropy, public=False)
        private_key = key.PrivateKey()
        public_key = key.PublicKey()
        wif = key.WalletImportFormat()

        sk = SigningKey.from_string(string=private_key,
                                    curve=ecdsa.SECP256k1,
                                    hashfunc=sha256)
        vk = sk.get_verifying_key()
        #print(public_key)

        output = sha256(public_key).digest()
        #print(binascii.hexlify(output))

        ripemd160 = hashlib.new('ripemd160')
        ripemd160.update(output)
        output = binascii.hexlify(ripemd160.digest())
        #print(output)

        output = b'3A' + output  # 3A is magic byte
        extended_ripmd160 = output
        #print(output)

        output = self.decode_hex(output)[0]
        output = sha256(output).digest()
        #print(binascii.hexlify(output))

        output = sha256(output).hexdigest().encode()
        #print(binascii.hexlify(output))

        checksum = output[:8]
        #print(checksum)

        output = extended_ripmd160 + checksum
        #print(output)

        output = self.decode_hex(output)[0]
        output = base58check.b58encode(output)
        #print(output)

        self.wif = wif
        self.private_key = private_key
        self.public_key = public_key
        self.uncompressed_public_key = vk.to_string()
        self.qtum_address = output
Beispiel #13
0
    def hex_address_to_blockchain_address(hex_address, mb):

        output = mb + hex_address
        extended_ripemd160 = output

        output = decode_hex(output)[0]

        checksum = sha256(sha256(output).digest()).hexdigest()[:8]

        output = extended_ripemd160 + checksum

        output = decode_hex(output)[0]
        output = base58check.b58encode(output)
        return output.decode()
Beispiel #14
0
def scriptpubkey_to_p2pkh_address(data: bytes) -> BTCAddress:
    """Return a P2PKH address given a scriptpubkey

    P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
    """
    if (data[0:1] != OpCodes.op_dup or data[1:2] != OpCodes.op_hash160
            or data[-2:-1] != OpCodes.op_equalverify
            or data[-1:] != OpCodes.op_checksig):
        raise EncodingError(f'Invalid P2PKH scriptpubkey: {data.hex()}')

    prefixed_hash = bytes.fromhex('00') + data[3:23]  # 20 byte pubkey hash
    checksum = hashlib.sha256(hashlib.sha256(prefixed_hash).digest()).digest()
    address = base58check.b58encode(prefixed_hash + checksum[:4])
    return BTCAddress(address.decode('ascii'))
Beispiel #15
0
 def get_address(cls, public_key):
     """
     地址是用过 公钥产生,算法是 RIPEMD160(SHA256(K)) ,在经过base58check编码的
     :param public_key:
     :return:
     """
     ripemd160 = hashlib.new('ripemd160',
                             hashlib.sha256(
                                 unhexlify(public_key)).digest()).digest()
     data = b'\x00' + ripemd160
     data_2_hash = hashlib.sha256(
         hashlib.sha256(data).digest()).digest()[:4]  # 两次hash256取前四个
     data = data + data_2_hash
     result = base58check.b58encode(data)
     return result
Beispiel #16
0
def pubkey_to_p2sh_p2wpkh_address(data: bytes) -> BTCAddress:
    """Bitcoin pubkey to PS2H-P2WPKH

    From here:
    https://bitcoin.stackexchange.com/questions/75910/how-to-generate-a-native-segwit-address-and-p2sh-segwit-address-from-a-standard
    """
    witprog = hash160(data)
    script = bytes.fromhex('0014') + witprog

    prefix = b'\x05'  # this is mainnet prefix -- we don't care about testnet
    # prefixed_hash, checksum = _calculate_hash160_and_checksum(prefix, prefix + script)
    prefixed_hash, checksum = _calculate_hash160_and_checksum(prefix, script)
    # address = base58check.b58encode(prefix + prefixed_hash + checksum[:4])
    address = base58check.b58encode(prefixed_hash + checksum[:4])
    return BTCAddress(address.decode('ascii'))
Beispiel #17
0
def pubkey_to_base58_address(data: bytes) -> BTCAddress:
    """
    Bitcoin pubkey to base58 address

    Source:
    https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses#How_to_create_Bitcoin_Address
    https://hackernoon.com/how-to-generate-bitcoin-addresses-technical-address-generation-explanation-rus3z9e

    May raise:
    - ValueError, TypeError due to b58encode
    """
    s4 = b'\x00' + hash160(data)
    s5 = hashlib.sha256(s4).digest()
    s6 = hashlib.sha256(s5).digest()
    return BTCAddress(base58check.b58encode(s4 + s6[:4]).decode('ascii'))
Beispiel #18
0
    def validate(self):
        """Validate the address."""
        if 25 > len(self.request.address) > 35:
            return False

        abytes = base58check.b58decode(self.request.address,
                                       **self.request.extras)
        if not abytes[0] in self.request.networks:
            return False

        checksum = sha256(sha256(abytes[:-4]).digest()).digest()[:4]
        if abytes[-4:] != checksum:
            return False

        return self.request.address == base58check.b58encode(
            abytes, **self.request.extras)
Beispiel #19
0
def generateWalletAddr(username, type):
    publicKey = getPublicKey(username, type)
    h = sha256()
    h.update(str(publicKey).encode('utf-8'))
    firstHash = h.hexdigest()
    h = new('ripemd160')
    h.update(str(firstHash).encode('utf-8'))
    ripemd160Hash = h.hexdigest()
    ripemd160HashExtd = '00' + ripemd160Hash
    h = sha256()
    h.update(str(ripemd160HashExtd).encode('utf-8'))
    hash2 = h.hexdigest()
    h.update(str(hash2).encode('utf-8'))
    hash3 = h.hexdigest()
    fourBytes = hash3[:8]
    binAddr = ripemd160HashExtd + fourBytes
    walletAddr = b58encode(str(binAddr).encode('utf-8'))
    return walletAddr.decode('ascii')
Beispiel #20
0
def is_valid_btc_address(value: str) -> bool:
    """Validates a bitcoin address for the mainnet

    Code is taken from:
    https://github.com/joeblackwaslike/coinaddr/blob/ae35c7ae550a687d9a7c2e0cb090d52edbb29cb5/coinaddr/validation.py#L67-L87

    """
    if 25 > len(value) > 35:
        return False

    abytes = base58check.b58decode(value)
    if not abytes[0] in (0x00, 0x05):
        return False

    checksum = sha256(sha256(abytes[:-4]).digest()).digest()[:4]
    if abytes[-4:] != checksum:
        return False

    return value == base58check.b58encode(abytes).decode()
Beispiel #21
0
    def _make_child_xpub(self, child_pubkey: PublicKey, index: int,
                         chain_code: bytes) -> str:
        """
        Makes a child xpub based on the current key and the child key info.
        Args:
            child_pubkey (bytes): the child pubkey
            index          (int): the child index
            chain_code   (bytes): the child chain code
        Returns
            (str): the child xpub
        """
        xpub = bytearray()

        xpub.extend(b58decode(cast(str, self.xpub))[0:4])  # prefix
        xpub.extend([cast(int, self.depth) + 1])  # depth
        xpub.extend(self.fingerprint)  # fingerprint
        xpub.extend(index.to_bytes(4, byteorder='big'))  # index
        xpub.extend(chain_code)  # chain_code
        xpub.extend(child_pubkey.format(COMPRESSED_PUBKEY))  # pubkey (comp)
        return b58encode(bytes(xpub)).decode('ascii')
Beispiel #22
0
def hex_sig_to_b58(hexsig: str) -> str:
    """Translate a hex signature to a tezos b58check encoding.

    Params:
        hexsig (str): hex string encoded signature

    Returns:
        str: b58check encoding of signature
    """
    def sha256(data):
        return hashlib.sha256(data).digest()
    bytes_sig = bytes.fromhex(hexsig)
    # Before translating to b58check encoding, we add a prefix at the beginning
    # of the sig, and a checksum at the end
    # The prefix enforces that the b58_sig starts with 'edsig's
    edsig_prefix = bytes([9, 245, 205, 134, 18])
    prefixed_bytes_sig = edsig_prefix + bytes_sig
    checksum = sha256(sha256(prefixed_bytes_sig))[0:4]
    final_sig = prefixed_bytes_sig + checksum
    b58_sig = base58check.b58encode(final_sig)
    return b58_sig.decode('ascii')
Beispiel #23
0
    def validate(self):
        """extended keys have their own validation"""
        if len(self.request.address) == 111:
            return self.validate_extended()
        """Validate the address."""
        if 25 > len(self.request.address) > 35:
            return False

        try:
            abytes = base58check.b58decode(self.request.address,
                                           **self.request.extras)
        except ValueError:
            return False

        if self.network == '':
            return False

        checksum = sha256(sha256(abytes[:-4]).digest()).digest()[:4]
        if abytes[-4:] != checksum:
            return False

        return self.request.address == base58check.b58encode(
            abytes, **self.request.extras)
Beispiel #24
0
    def to_string(self):
        """Returns as address string

        |  Pseudocode:
        |      network_prefix = (1 byte version number)
        |      data = network_prefix + hash160_bytes
        |      data_hash = SHA-256( SHA-256( hash160_bytes ) )
        |      checksum = (first 4 bytes of data_hash)
        |      address_bytes = Base58CheckEncode( data + checksum )
        """
        hash160_encoded = self.hash160.encode('utf-8')
        hash160_bytes = unhexlify(hash160_encoded)

        if self.get_type() == P2PKH_ADDRESS:
            data = NETWORK_P2PKH_PREFIXES[get_network()] + hash160_bytes
        elif self.get_type() == P2SH_ADDRESS:
            data = NETWORK_P2SH_PREFIXES[get_network()] + hash160_bytes

        data_hash = hashlib.sha256(hashlib.sha256(data).digest()).digest()
        checksum = data_hash[0:4]
        address_bytes = b58encode(data + checksum)

        return address_bytes.decode('utf-8')
Beispiel #25
0
exit(0)
for i in bb:
    for j in bb:
        c += 1
        # Add 2 random bytes to the secret key starting
        wipd_test = wipd_fake_starting + i + j

        # Calc SHA256(WIPd)
        h = hashlib.sha256()
        h.update(wipd_test)
        wipd_sha256 = h.digest()

        # Calc SHA256(SHA256(WIPd))
        h = hashlib.sha256()
        h.update(wipd_sha256)
        wipd_sha256x2 = h.digest()

        # Get checksum (first 4 bytes from hash)
        checksum = wipd_sha256x2[:4]
        # Concat WIPd and checksum
        wip_key = base58check.b58encode(wipd_test+checksum)
        # Generate wallet address
        k = key.Key.from_text(wip_key.decode())

        if c % 1024 == 0:
            print(f'{c:5} keys checked...')
        if wallet == k.address():
            print(f'{c:5} GOTCHA! {wallet} == {k.address()}')
            print(f'WIP key: {wip_key.decode()}')
            exit(0)
Beispiel #26
0
}
info("Getting public keys from HSM")
kvurl = 'https://' + config['kv_name_domain'] + '.vault.azure.net'
kvclient = KeyVaultClient(
    MSIAuthentication(resource='https://vault.azure.net'))
keys = kvclient.get_keys(kvurl)
for key in keys:
    keyname = key.kid.split('/')
    keydat = kvclient.get_key(kvurl, keyname[-1], '').key

    parity = bytes([2])
    if int.from_bytes(keydat.y, 'big') % 2 == 1:
        parity = bytes([3])
    shabytes = sha256(sha256(P2PK_MAGIC + parity +
                             keydat.x).digest()).digest()[:4]
    public_key = b58encode(P2PK_MAGIC + parity + keydat.x + shabytes).decode()
    blake2bhash = blake2b(parity + keydat.x, digest_size=20).digest()
    shabytes = sha256(sha256(P2HASH_MAGIC + blake2bhash).digest()).digest()[:4]
    pkhash = b58encode(P2HASH_MAGIC + blake2bhash + shabytes).decode()

    config['keys'].update(
        {pkhash: {
            'kv_keyname': keyname[-1],
            'public_key': public_key
        }})
    info('retrieved key info: kevault keyname: ' + keyname[-1] + ' pkhash: ' +
         pkhash + ' - public_key: ' + public_key)


@app.route('/keys/<key_hash>', methods=['POST'])
def sign(key_hash):
Beispiel #27
0
#!/usr/bin/env python3
 
from hashlib import sha256, blake2b
from base58check import b58encode
import nacl.signing
from sys import argv

edsklongprefix = bytes.fromhex('2bf64e07') # decimal is { (byte) 43, (byte) 246, (byte) 78, (byte) 7 };
edpkPrefix = bytes.fromhex('0d0f25d9') # decimal is { (byte) 13, (byte) 15, (byte) 37, (byte) 217 };
tz1prefix =  bytes.fromhex('06a19f') # decimal is { (byte) 6, (byte) 161, (byte) 159 };

for a in range (1, 999999999999999999):
    signing_key = nacl.signing.SigningKey.generate()
    publicbytes = signing_key.verify_key.encode()
    blake2bhash = blake2b(publicbytes, digest_size=20).digest()
    shabytes = sha256(sha256(tz1prefix + blake2bhash).digest()).digest()[:4]
    pkhash = b58encode(tz1prefix + blake2bhash + shabytes).decode()    
    if pkhash[3:len(argv[1])+3] == argv[1]:
        privatebytes = signing_key.encode() + publicbytes
        prefixedprivatebytes = edsklongprefix + privatebytes
        shabytes = sha256(sha256(prefixedprivatebytes).digest()).digest()[:4]
        edsk = b58encode(prefixedprivatebytes+shabytes).decode()
        print(f"{a:,d}")
        print(edsk)
        print(pkhash)
        break
    if a % 10000 == 0: print(f"{a:,d}")
Beispiel #28
0
 def gen_address(self, pubkey: bytes):
     log.info(
         f'Generating Wallet address for public key {pubkey.hex()[:4]}...')
     pub_ripemd = RIPEMD.new(SHA256.new(pubkey).digest())
     pub_b58 = b58encode(pub_ripemd.digest())
     return pub_b58
Beispiel #29
0
x = verifying_key.pubkey.point.x()
x = pairEncode(f'{x:x}')
y = verifying_key.pubkey.point.y()
y = pairEncode(f'{y:x}')

full_public_key = b'\x00' + x + y

# Compress the public key.
prefix = b'\x03' if y[-1] % 2 else b'\x02'
public_key = prefix + x

# Calculate the address.
# Encrypt public key.
public_hash = hasher(public_key, 'sha256')
encrypted_public_key = hasher(public_hash, 'ripemd160')

# Add network byte (main: 0x00, test:0x6f)
encrypted_public_key = b'\x00' + encrypted_public_key

# Calculate the checksum.
checksum = hasher(encrypted_public_key, 'sha256')
checksum = hasher(checksum, 'sha256')
checksum = checksum[:4]  # last 4 bytes

# Merge mainnet key and checksum and encode with base58check to make address.
address = b58encode(encrypted_public_key + checksum).decode('ascii')

print(f'Private Key: {private_key:x}')
print('Public Key:', public_key.hex())
print('Address:', address)
Beispiel #30
0
#!/usr/bin/env python3

from hashlib import sha256, blake2b
from base58check import b58encode
import nacl.signing

edsklongprefix = bytes.fromhex(
    '2bf64e07')  # decimal is { (byte) 43, (byte) 246, (byte) 78, (byte) 7 };
edpkPrefix = bytes.fromhex(
    '0d0f25d9')  # decimal is { (byte) 13, (byte) 15, (byte) 37, (byte) 217 };
tz1prefix = bytes.fromhex(
    '06a19f')  # decimal is { (byte) 6, (byte) 161, (byte) 159 };

signing_key = nacl.signing.SigningKey.generate()
verify_key = signing_key.verify_key
publicbytes = verify_key.encode()
privatebytes = signing_key.encode() + publicbytes

prefixedprivatebytes = edsklongprefix + privatebytes
shabytes = sha256(sha256(prefixedprivatebytes).digest()).digest()[:4]
print(b58encode(prefixedprivatebytes + shabytes).decode())

prefixedpub = edpkPrefix + publicbytes
shabytes = sha256(sha256(prefixedpub).digest()).digest()[:4]
print(b58encode(prefixedpub + shabytes).decode())

blake2bhash = blake2b(publicbytes, digest_size=20).digest()
shabytes = sha256(sha256(tz1prefix + blake2bhash).digest()).digest()[:4]
print(b58encode(tz1prefix + blake2bhash + shabytes).decode())