Unwraps the private key into an RSAPrivateKey, DSAPrivateKey or
        ECPrivateKey object

        :return:
            An RSAPrivateKey, DSAPrivateKey or ECPrivateKey object
173409
def unwrap(self):
        

        if self.algorithm == 'rsa':
            return self['private_key'].parsed

        if self.algorithm == 'dsa':
            params = self['private_key_algorithm']['parameters']
            return DSAPrivateKey({
                'version': 0,
                'p': params['p'],
                'q': params['q'],
                'g': params['g'],
                'public_key': self.public_key,
                'private_key': self['private_key'].parsed,
            })

        if self.algorithm == 'ec':
            output = self['private_key'].parsed
            output['parameters'] = self['private_key_algorithm']['parameters']
            output['public_key'] = self.public_key
            return output
839346
def public_key(self):
        

        if self._public_key is None:
            if self.algorithm == 'ec':
                key = self['private_key'].parsed
                if key['public_key']:
                    self._public_key = key['public_key'].untag()
                else:
                    self._public_key = self._compute_public_key()
            else:
                self._public_key = self._compute_public_key()

        return self._public_key
961143
def from_str(cls: Type[CRCPubkeyType], crc_pubkey: str) -> CRCPubkeyType:
        
        data = CRCPubkey.re_crc_pubkey.match(crc_pubkey)
        if data is None:
            raise Exception("Could not parse CRC public key {0}".format(crc_pubkey))
        pubkey = data.group(1)
        crc = data.group(2)
        return cls(pubkey, crc)
736658
def from_passphrase(cls, passphrase=None):
        
        if not passphrase:
            # run a rejection sampling algorithm to ensure the private key is
            # less than the curve order
            while True:
                passphrase = create_passphrase(bits_of_entropy=160)
                hex_private_key = hashlib.sha256(passphrase).hexdigest()
                if int(hex_private_key, 16) < cls._curve.order:
                    break
        else:
            hex_private_key = hashlib.sha256(passphrase).hexdigest()
            if not (int(hex_private_key, 16) < cls._curve.order):
                raise ValueError(_errors["PHRASE_YIELDS_INVALID_EXPONENT"])

        keypair = cls(hex_private_key)
        keypair._passphrase = passphrase
        return keypair
25832
def generate(cls):
        
        return cls(libnacl.randombytes(PrivateKey.SIZE), encoder=encoding.RawEncoder)
1084671
def from_private_key(path: str) -> SigningKeyType:
        
        key = load_key(path)
        key.pubkey = Base58Encoder.encode(key.vk)
        return key
516047
def get_key
      # check for a private key string
      if encoded_key = Gxapi.config.google.respond_to?(:private_key)
        OpenSSL::PKey::RSA.new(
          Base64.decode64(Gxapi.config.google.private_key),
          'notasecret'
        )
      else
        Google::APIClient::KeyUtils.load_from_pkcs12(
          Gxapi.config.google.private_key_path,
          'notasecret'
        )
      end
    end
1197976
def encrypt_item(table_name, rsa_wrapping_private_key_bytes, rsa_signing_private_key_bytes):
    """"""
    index_key = {"partition_attribute": "is this", "sort_attribute": 55}
    plaintext_item = {
        "example": "data",
        "some numbers": 99,
        "and some binary": Binary(b"\x00\x01\x02"),
        "leave me": "alone",  # We want to ignore this attribute
    }
    # Collect all of the attributes that will be encrypted (used later).
    encrypted_attributes = set(plaintext_item.keys())
    encrypted_attributes.remove("leave me")
    # Collect all of the attributes that will not be encrypted (used later).
    unencrypted_attributes = set(index_key.keys())
    unencrypted_attributes.add("leave me")
    # Add the index pairs to the item.
    plaintext_item.update(index_key)

    # Create a normal table resource.
    table = boto3.resource("dynamodb").Table(table_name)
    # Create a crypto materials provider using the provided wrapping and signing keys.
    # We show private keys used here, but public keys could be used as well, allowing
    # only wrapping or signature verification.
    wrapping_key = JceNameLocalDelegatedKey(
        key=rsa_wrapping_private_key_bytes,
        algorithm="RSA",
        key_type=EncryptionKeyType.PRIVATE,
        key_encoding=KeyEncodingType.DER,
    )
    signing_key = JceNameLocalDelegatedKey(
        key=rsa_signing_private_key_bytes,
        algorithm="SHA512withRSA",
        key_type=EncryptionKeyType.PRIVATE,
        key_encoding=KeyEncodingType.DER,
    )
    wrapped_cmp = WrappedCryptographicMaterialsProvider(
        wrapping_key=wrapping_key, unwrapping_key=wrapping_key, signing_key=signing_key
    )
    # Create attribute actions that tells the encrypted table to encrypt all attributes except one.
    actions = AttributeActions(
        default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"leave me": CryptoAction.DO_NOTHING}
    )
    # Use these objects to create an encrypted table resource.
    encrypted_table = EncryptedTable(table=table, materials_provider=wrapped_cmp, attribute_actions=actions)

    # Put the item to the table, using the encrypted table resource to transparently encrypt it.
    encrypted_table.put_item(Item=plaintext_item)

    # Get the encrypted item using the standard table resource.
    encrypted_item = table.get_item(Key=index_key)["Item"]

    # Get the item using the encrypted table resource, transparently decyrpting it.
    decrypted_item = encrypted_table.get_item(Key=index_key)["Item"]

    # Verify that all of the attributes are different in the encrypted item
    for name in encrypted_attributes:
        assert encrypted_item[name] != plaintext_item[name]
        assert decrypted_item[name] == plaintext_item[name]

    # Verify that all of the attributes that should not be encrypted were not.
    for name in unencrypted_attributes:
        assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]

    # Clean up the item
    encrypted_table.delete_item(Key=index_key)
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key
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)
1156449
def make_pkey(key_type=crypto.TYPE_RSA, key_bits=4096):
  
  key = crypto.PKey()
  key.generate_key(key_type, key_bits)
  return key
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
1022451
def encrypt(self, keys=None, cek="", iv="", **kwargs):
        

        _alg = self["alg"]

        # Find Usable Keys
        if keys:
            keys = self.pick_keys(keys, use="enc")
        else:
            keys = self.pick_keys(self._get_keys(), use="enc")

        if not keys:
            logger.error(KEY_ERR.format(_alg))
            raise NoSuitableEncryptionKey(_alg)

        # Determine Encryption Class by Algorithm
        if _alg in ["RSA-OAEP", "RSA-OAEP-256", "RSA1_5"]:
            encrypter = JWE_RSA(self.msg, **self._dict)
        elif _alg.startswith("A") and _alg.endswith("KW"):
            encrypter = JWE_SYM(self.msg, **self._dict)
        else:  # _alg.startswith("ECDH-ES"):
            encrypter = JWE_EC(**self._dict)
            cek, encrypted_key, iv, params, eprivk = encrypter.enc_setup(
                self.msg, key=keys[0], **self._dict)
            kwargs["encrypted_key"] = encrypted_key
            kwargs["params"] = params

        if cek:
            kwargs["cek"] = cek

        if iv:
            kwargs["iv"] = iv

        for key in keys:
            if isinstance(key, SYMKey):
                _key = key.key
            elif isinstance(key, ECKey):
                _key = key.public_key()
            else:  # isinstance(key, RSAKey):
                _key = key.public_key()

            if key.kid:
                encrypter["kid"] = key.kid

            try:
                token = encrypter.encrypt(key=_key, **kwargs)
                self["cek"] = encrypter.cek if 'cek' in encrypter else None
            except TypeError as err:
                raise err
            else:
                logger.debug(
                    "Encrypted message using key with kid={}".format(key.kid))
                return token
626714
def authnkey(self) -> dict:
        

        return {k: self._pubkey[k] for k in self._pubkey if self._pubkey[k].authn}
1131624
def private_key_to_address(private_key: Union[str, bytes]) -> ChecksumAddress:
    
    if isinstance(private_key, str):
        private_key_bytes = to_bytes(hexstr=private_key)
    else:
        private_key_bytes = private_key
    pk = PrivateKey(private_key_bytes)
    return public_key_to_address(pk.public_key)
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
625194
def decrypt(self, message):
        

        # Unserialize the encrypted message
        message = json.loads(message)

        # Set up a list for the unencrypted lines of the message
        unencrypted_msg = []

        for line in message:

            # Convert from ascii back to bytestring
            enc_line = binascii.a2b_base64(line)

            # Decrypt the line using our private key
            unencrypted_line = rsa.decrypt(enc_line, self.private_key)

            unencrypted_msg.append(unencrypted_line)

        # Convert the message from a list back into a string
        unencrypted_msg = "".join(unencrypted_msg)

        return unencrypted_msg