Derives a child private key from a parent
        private key. It is not possible to derive a child
        private key from a public parent key.

        Args:
            parent_private_key (HDPrivateKey):
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)
416295
def private_key_from_der_format(der_key)
      raise ArgumentError, "Missing DER private key" if !der_key

      prepare_if_needed

      buf = FFI::MemoryPointer.from_string(der_key)
      ec_key = d2i_ECPrivateKey(nil, pointer_to_pointer(buf), buf.size-1)
      if ec_key.null?
        raise BTCError, "OpenSSL failed to create EC_KEY with DER private key"
      end
      bn = EC_KEY_get0_private_key(ec_key)
      BN_bn2bin(bn, buf)
      buf.read_string(32)
    end
1096590
def add(self, private_key):
        
        if not isinstance(private_key, PaillierPrivateKey):
            raise TypeError("private_key should be of type PaillierPrivateKey, "
                            "not %s" % type(private_key))
        self.__keyring[private_key.public_key] = private_key
1096075
private function ensureParentAndKey($parent, $key)
    {
        if (!$this->parent)
        {
            $this->parent = $parent;
        }
        if (!$this->key)
        {
            $this->key = $key;
        }
        if ($this->parent != $parent)
        {
            throw new \Exception('Internal Error. Relation retrieved from two different Objects.');
        }
        if ($this->key != $key)
        {
            throw new \Exception('Internal Error. Relation retrieved from two different keys.');
        }
    }
397041
private int ascertainParentFingerprint(DeterministicKey parentKey, int parentFingerprint)
    throws IllegalArgumentException {
        if (parentFingerprint != 0) {
            if (parent != null)
                checkArgument(parent.getFingerprint() == parentFingerprint,
                              "parent fingerprint mismatch",
                              Integer.toHexString(parent.getFingerprint()), Integer.toHexString(parentFingerprint));
            return parentFingerprint;
        } else return 0;
    }
798168
def _load_private_key(self, private_key, passphrase=None):
        
        key = None
        last_exception = None
        for pkey_class in (RSAKey, DSSKey):
            try:
                key = pkey_class.from_private_key(StringIO(private_key),
                    passphrase)
            except PasswordRequiredException as e:
                # The key file is encrypted and no passphrase was provided.
                # There's no point to continue trying
                raise
            except SSHException as e:
                last_exception = e
                continue
            else:
                break
        if key is None and last_exception:
            raise last_exception
        return key
932047
public static PrivateKey createPrivateKey(byte[] privateKey) {
    if (privateKey == null) {
      return null;
    }

    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
      return fac.generatePrivate(spec);
    }
    catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e);
    }
    catch (InvalidKeySpecException e) {
      throw new IllegalStateException(e);
    }
  }
547461
def key_from_jwk_dict(jwk_dict, private=None):
    

    # uncouple from the original item
    _jwk_dict = copy.copy(jwk_dict)

    if 'kty' not in _jwk_dict:
        raise MissingValue('kty missing')

    if _jwk_dict['kty'] == 'EC':
        ensure_ec_params(_jwk_dict, private)

        if private is not None and not private:
            # remove private components
            for v in EC_PRIVATE:
                _jwk_dict.pop(v, None)

        if _jwk_dict["crv"] in NIST2SEC:
            curve = NIST2SEC[_jwk_dict["crv"]]()
        else:
            raise UnsupportedAlgorithm(
                "Unknown curve: %s" % (_jwk_dict["crv"]))

        if _jwk_dict.get("d", None) is not None:
            # Ecdsa private key.
            _jwk_dict['priv_key'] = ec.derive_private_key(
                base64url_to_long(_jwk_dict["d"]), curve,
                backends.default_backend())
            _jwk_dict['pub_key'] = _jwk_dict['priv_key'].public_key()
        else:
            # Ecdsa public key.
            ec_pub_numbers = ec.EllipticCurvePublicNumbers(
                base64url_to_long(_jwk_dict["x"]),
                base64url_to_long(_jwk_dict["y"]), curve)
            _jwk_dict['pub_key'] = ec_pub_numbers.public_key(
                backends.default_backend())
        return ECKey(**_jwk_dict)
    elif _jwk_dict['kty'] == 'RSA':
        ensure_rsa_params(_jwk_dict, private)

        if private is not None and not private:
            # remove private components
            for v in RSA_PRIVATE:
                _jwk_dict.pop(v, None)

        rsa_pub_numbers = rsa.RSAPublicNumbers(
            base64url_to_long(_jwk_dict["e"]),
            base64url_to_long(_jwk_dict["n"]))
        if _jwk_dict.get("p", None) is not None:
            # Rsa private key. These MUST be present
            p_long = base64url_to_long(_jwk_dict["p"])
            q_long = base64url_to_long(_jwk_dict["q"])
            d_long = base64url_to_long(_jwk_dict["d"])
            # If not present these can be calculated from the others
            if 'dp' not in _jwk_dict:
                dp_long = rsa_crt_dmp1(d_long, p_long)
            else:
                dp_long = base64url_to_long(_jwk_dict["dp"])
            if 'dq' not in _jwk_dict:
                dq_long = rsa_crt_dmq1(d_long, q_long)
            else:
                dq_long = base64url_to_long(_jwk_dict["dq"])
            if 'qi' not in _jwk_dict:
                qi_long = rsa_crt_iqmp(p_long, q_long)
            else:
                qi_long = base64url_to_long(_jwk_dict["qi"])

            rsa_priv_numbers = rsa.RSAPrivateNumbers(
                p_long, q_long, d_long,
                dp_long, dq_long, qi_long, rsa_pub_numbers)
            _jwk_dict['priv_key'] = rsa_priv_numbers.private_key(
                backends.default_backend())
            _jwk_dict['pub_key'] = _jwk_dict['priv_key'].public_key()
        else:
            _jwk_dict['pub_key'] = rsa_pub_numbers.public_key(
                backends.default_backend())

        if _jwk_dict['kty'] != "RSA":
            raise WrongKeyType('"{}" should have been "RSA"'.format(_jwk_dict[
                                                                        'kty']))
        return RSAKey(**_jwk_dict)
    elif _jwk_dict['kty'] == 'oct':
        if 'key' not in _jwk_dict and 'k' not in _jwk_dict:
            raise MissingValue(
                'There has to be one of "k" or "key" in a symmetric key')

        return SYMKey(**_jwk_dict)
    else:
        raise UnknownKeyType
702444
def create_header_from_parent(self,
                                  parent_header: BlockHeader,
                                  **header_params: HeaderParams) -> BlockHeader:
        
        return self.get_vm_class_for_block_number(
            block_number=parent_header.block_number + 1,
        ).create_header_from_parent(parent_header, **header_params)
1216020
def parent(self, parent):
        
        self._name = self.unique_name(self._name)
        self._full_name = None
        self._logger = None
        self._parent = parent
1042053
def generate_key(self):
        
        req = self.request(self.uri + "/keys")
        private_key = req.post().json()
        return private_key['priv']
643674
def generate_public_key(self):
        
        self.public_key = pow(self.generator,
                              self.__private_key,
                              self.prime)
20663
def get_derived_from(self, address):
    
    parent_address = self._derived_from_by_derivative.get(address, address)
    return self.get_target(parent_address)
693046
def _inherit_parent_kwargs(self, kwargs):
        

        if not self.parent or not self._is_dynamic:
            return kwargs

        if 'request_fields' not in kwargs:
            # If 'request_fields' isn't explicitly set, pull it from the
            # parent serializer.
            request_fields = self._get_request_fields_from_parent()
            if request_fields is None:
                # Default to 'id_only' for nested serializers.
                request_fields = True
            kwargs['request_fields'] = request_fields

        if self.embed and kwargs.get('request_fields') is True:
            # If 'embed' then make sure we fetch the full object.
            kwargs['request_fields'] = {}

        if hasattr(self.parent, 'sideloading'):
            kwargs['sideloading'] = self.parent.sideloading

        if hasattr(self.parent, 'debug'):
            kwargs['debug'] = self.parent.debug

        return kwargs
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
869466
def parent(self, key):
        """"""
        parent_key = '.'.join(key.split('.')[:-1])
        if not parent_key:
            return None
        else:
            return self[parent_key]
347183
def parent(self, parent):
        
        self._parent = parent
        if parent:
            pctx = dict((x, getattr(parent, x)) for x in parent.context_keys)
            self.inject_context(pctx)
            self.depth = parent.depth + 1
            for command in self.subcommands.values():
                command.parent = self  # bump.
        else:
            self.depth = 0