Parse a bip32 private key from a text string ("xprv" type).
        Return a :class:`BIP32 <pycoin.key.BIP32Node.BIP32Node>` or None.
175729
def bip32_prv(self, s):
        
        data = self.parse_b58_hashed(s)
        if data is None or not data.startswith(self._bip32_prv_prefix):
            return None
        return self._network.keys.bip32_deserialize(data)
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')
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]
304196
def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType:
        
        hash_root = hashlib.sha256()
        hash_root.update(base58.b58decode(pubkey))
        hash_squared = hashlib.sha256()
        hash_squared.update(hash_root.digest())
        b58_checksum = ensure_str(base58.b58encode(hash_squared.digest()))

        crc = b58_checksum[:3]
        return cls(pubkey, crc)
620966
def parse(self, text):
        
        root = ET.fromstring(text)
        for elm in root.findall('{http://www.iana.org/assignments}registry'):
            for record in elm.findall('{http://www.iana.org/assignments}record'):
                for fileElm in record.findall('{http://www.iana.org/assignments}file'):
                    if fileElm.get('type') == 'template':
                        mimeType = fileElm.text.strip()
                        yield mimeType
                        break
1332353
def parse_from_string(
        root_processor,  # type: RootProcessor
        xml_string  # type: Text
):
    # type: (...) -> Any
    
    if not _is_valid_root_processor(root_processor):
        raise InvalidRootProcessor('Invalid root processor')

    parseable_xml_string = xml_string  # type: Union[Text, bytes]
    if _PY2 and isinstance(xml_string, Text):
        parseable_xml_string = xml_string.encode('utf-8')

    root = ET.fromstring(parseable_xml_string)
    _xml_namespace_strip(root)

    state = _ProcessorState()
    state.push_location(root_processor.element_path)
    return root_processor.parse_at_root(root, state)
1075890
def _load_rsa_private_key(pem):
    """"""
    # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support
    # them natively. Do some ASN unwrapping to extract naked RSA key
    # (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt.
    # Also http://superuser.com/a/606266.
    try:
        der = rsa.pem.load_pem(pem, 'PRIVATE KEY')
        keyinfo, _ = decoder.decode(der)
        if keyinfo[1][0] != univ.ObjectIdentifier(
                '1.2.840.113549.1.1.1'):  # pragma: no cover
            raise ValueError('Not a DER-encoded OpenSSL private RSA key')
        private_key_der = keyinfo[2].asOctets()
    except IndexError:  # pragma: no cover
        raise ValueError('Not a DER-encoded OpenSSL private RSA key')
    return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER')
904308
def private_key(self, s):
        
        s = parseable_str(s)
        for f in [self.wif, self.secret_exponent]:
            v = f(s)
            if v:
                return v
659837
def private_key_type(key_file):
    

    keytypes = (("RSA", RSA), ("DSA", DSA), ("EC", EC))

    for key, ktype in keytypes:
        try:
            ktype.load_key(key_file)
        except (RSA.RSAError, DSA.DSAError, ValueError):
            continue
        else:
            return key
    else:
        raise CannotFindKeyTypeError()
194699
def parse_message(self, msg, msg_signature, timestamp, nonce):
        
        content = self.crypto.decrypt_message(msg, msg_signature, timestamp, nonce)
        message = xmltodict.parse(to_text(content))['xml']
        message_type = message['InfoType'].lower()
        message_class = COMPONENT_MESSAGE_TYPES.get(message_type, ComponentUnknownMessage)
        msg = message_class(message)
        if msg.type == 'component_verify_ticket':
            self.session.set(msg.type, msg.verify_ticket)
        elif msg.type in ('authorized', 'updateauthorized'):
            msg.query_auth_result = self.query_auth(msg.authorization_code)
        return msg
965905
def from_parent(parent_key, i):
        
        if not isinstance(parent_key, HDPrivateKey):
            raise TypeError("parent_key must be an HDPrivateKey object.")

        hmac_key = parent_key.chain_code
        if i & 0x80000000:
            hmac_data = b'\x00' + bytes(parent_key._key) + i.to_bytes(length=4, byteorder='big')
        else:
            hmac_data = parent_key.public_key.compressed_bytes + i.to_bytes(length=4, byteorder='big')

        I = hmac.new(hmac_key, hmac_data, hashlib.sha512).digest()
        Il, Ir = I[:32], I[32:]

        parse_Il = int.from_bytes(Il, 'big')
        if parse_Il >= bitcoin_curve.n:
            return None

        child_key = (parse_Il + parent_key._key.key) % bitcoin_curve.n

        if child_key == 0:
            # Incredibly unlucky choice
            return None

        child_depth = parent_key.depth + 1
        return HDPrivateKey(key=child_key,
                            chain_code=Ir,
                            index=i,
                            depth=child_depth,
                            parent_fingerprint=parent_key.fingerprint)
1021520
def rfc6979_ecdsa_nonce(hash, privkey)
      raise ArgumentError, "Hash must be 32 bytes long" if hash.bytesize != 32
      raise ArgumentError, "Private key must be 32 bytes long" if privkey.bytesize != 32

      autorelease do |pool|
        order = self.group_order

        # Step 3.2.a. hash = H(message). Already performed by the caller.

        # Step 3.2.b. V = 0x01 0x01 0x01 ... 0x01 (32 bytes equal 0x01)
        v = "\x01".b*32

        # Step 3.2.c. K = 0x00 0x00 0x00 ... 0x00 (32 bytes equal 0x00)
        k = "\x00".b*32

        # Step 3.2.d. K = HMAC-SHA256(key: K, data: V || 0x00 || int2octets(privkey) || bits2octets(hash))
        h1 = pool.new_bn(hash)
        BN_div(nil, h1, h1, order, pool.bn_ctx) # h1 = h1 % order
        h1data = data_from_bn(h1, min_length: 32)
        k = BTC.hmac_sha256(key: k, data: v + "\x00".b + privkey + h1data)

        # Step 3.2.e. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.f. K = HMAC-SHA256(key: K, data: V || 0x01 || int2octets(privkey) || bits2octets(hash))
        k = BTC.hmac_sha256(key: k, data: v + "\x01".b + privkey + h1data)

        # Step 3.2.g. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.h.
        zero32 = "\x00".b*32
        10000.times do
          t = BTC.hmac_sha256(key: k, data: v)
          tn = pool.new_bn(t)
          if BN_cmp(tn, order) < 0
            nonce = data_from_bn(tn, min_length: 32)
            if nonce != zero32
              return nonce
            end
          end
          # Note: the probability of not succeeding at the first try is about 2^-127.
          k = BTC.hmac_sha256(key: k, data: v + zero32)
          v = BTC.hmac_sha256(key: k, data: v)
        end
        # we generated 10000 numbers, none of them is good -> fail.
        raise "Cannot find any good ECDSA nonce after 10000 iterations of RFC6979."
      end
    end
477511
def ascend_bip32(bip32_pub_node, secret_exponent, child):
    
    i_as_bytes = struct.pack(">l", child)
    sec = public_pair_to_sec(bip32_pub_node.public_pair(), compressed=True)
    data = sec + i_as_bytes
    I64 = hmac.HMAC(key=bip32_pub_node._chain_code, msg=data, digestmod=hashlib.sha512).digest()
    I_left_as_exponent = from_bytes_32(I64[:32])
    return (secret_exponent - I_left_as_exponent) % bip32_pub_node._generator.order()
1227004
def parse( bin_payload, sender_script, recipient_address ):
    
   
   if len(bin_payload) < MIN_OP_LENGTHS['namespace_reveal']:
       raise AssertionError("Payload is too short to be a namespace reveal")

   off = 0
   life = None 
   coeff = None 
   base = None 
   bucket_hex = None
   buckets = []
   discount_hex = None
   nonalpha_discount = None 
   no_vowel_discount = None
   version = None
   namespace_id = None 
   namespace_id_hash = None
   
   life = int( hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_life']]), 16 )
   
   off += LENGTHS['blockchain_id_namespace_life']
   
   coeff = int( hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_coeff']]), 16 )
   
   off += LENGTHS['blockchain_id_namespace_coeff']
   
   base = int( hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_base']]), 16 )
   
   off += LENGTHS['blockchain_id_namespace_base']
   
   bucket_hex = hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_buckets']])
   
   off += LENGTHS['blockchain_id_namespace_buckets']
   
   discount_hex = hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_discounts']])
   
   off += LENGTHS['blockchain_id_namespace_discounts']
   
   version = int( hexlify(bin_payload[off:off+LENGTHS['blockchain_id_namespace_version']]), 16)
   
   off += LENGTHS['blockchain_id_namespace_version']
   
   namespace_id = bin_payload[off:]
   namespace_id_hash = None
   try:
       namespace_id_hash = hash_name( namespace_id, sender_script, register_addr=recipient_address )
   except:
       log.error("Invalid namespace ID and/or sender script")
       return None
   
   # extract buckets 
   buckets = [int(x, 16) for x in list(bucket_hex)]
   
   # extract discounts
   nonalpha_discount = int( list(discount_hex)[0], 16 )
   no_vowel_discount = int( list(discount_hex)[1], 16 )
  
   try:
       rc = namespacereveal_sanity_check( namespace_id, version, life, coeff, base, buckets, nonalpha_discount, no_vowel_discount )
       if not rc:
           raise Exception("Invalid namespace parameters")

   except Exception, e:
       if BLOCKSTACK_TEST:
           log.exception(e)

       log.error("Invalid namespace parameters")
       return None 

   return {
      'opcode': 'NAMESPACE_REVEAL',
      'lifetime': life,
      'coeff': coeff,
      'base': base,
      'buckets': buckets,
      'version': version,
      'nonalpha_discount': nonalpha_discount,
      'no_vowel_discount': no_vowel_discount,
      'namespace_id': namespace_id,
      'preorder_hash': namespace_id_hash
   }
1019784
def create_key_pair(self, cert_type, bits):
        

        pkey = crypto.PKey()
        pkey.generate_key(cert_type, bits)
        return pkey
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
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