示例#1
0
    def __init__(self,
                 character_flag: Union[ALICE, BOB],
                 verifying_key: Union[PublicKey, bytes],
                 encrypting_key: Optional[Union[PublicKey, bytes]] = None,
                 nickname: Optional[Union[bytes, str]] = None):

        try:
            self.__character_class = self.__CARD_TYPES[bytes(character_flag)]
        except KeyError:
            raise ValueError(f'Unsupported card type {str(character_flag)}')
        self.__character_flag = character_flag

        if isinstance(verifying_key, bytes):
            verifying_key = PublicKey.from_bytes(verifying_key)
        self.__verifying_key = verifying_key  # signing public key

        if isinstance(encrypting_key, bytes):
            encrypting_key = PublicKey.from_bytes(encrypting_key)
        self.__encrypting_key = encrypting_key  # public key

        if isinstance(nickname, str):
            nickname = nickname.encode()
        self.__nickname = nickname

        self.__validate()
示例#2
0
    def retrieve(self,
                 label: bytes,
                 policy_encrypting_key: bytes,
                 alice_verifying_key: bytes,
                 message_kit: bytes,
                 treasure_map: Union[bytes, str, 'TreasureMap'] = None):
        """
        Character control endpoint for re-encrypting and decrypting policy data.
        """
        from nucypher.characters.lawful import Enrico

        policy_encrypting_key = PublicKey.from_bytes(policy_encrypting_key)
        alice_verifying_key = PublicKey.from_bytes(alice_verifying_key)
        message_kit = UmbralMessageKit.from_bytes(
            message_kit
        )  # TODO #846: May raise UnknownOpenSSLError and InvalidTag.

        enrico = Enrico.from_public_keys(
            verifying_key=message_kit.sender_verifying_key,
            policy_encrypting_key=policy_encrypting_key,
            label=label)

        self.character.join_policy(label=label,
                                   alice_verifying_key=alice_verifying_key)

        plaintexts = self.character.retrieve(
            message_kit,
            enrico=enrico,
            alice_verifying_key=alice_verifying_key,
            label=label,
            treasure_map=treasure_map)

        response_data = {'cleartexts': plaintexts}
        return response_data
示例#3
0
 def convert(self, value, param, ctx):
     if self.validate:
         try:
             _key = PublicKey.from_bytes(bytes.fromhex(value))
         except (InternalError, ValueError):
             self.fail(f"'{value}' is not a valid nucypher public key.")
     return value
示例#4
0
    def from_public_keys(cls,
                         powers_and_material: Dict = None,
                         verifying_key: Union[bytes, PublicKey] = None,
                         encrypting_key: Union[bytes, PublicKey] = None,
                         *args,
                         **kwargs) -> 'Character':
        """
        Sometimes we discover a Character and, at the same moment,
        learn the public parts of more of their powers. Here, we take a Dict
        (powers_and_material) in the format {CryptoPowerUp class: material},
        where material can be bytes or umbral.PublicKey.

        Each item in the collection will have the CryptoPowerUp instantiated
        with the given material, and the resulting CryptoPowerUp instance
        consumed by the Character.

        Alternatively, you can pass directly a verifying public key
        (for SigningPower) and/or an encrypting public key (for DecryptionPower).
        """
        crypto_power = CryptoPower()

        if powers_and_material is None:
            powers_and_material = dict()

        if verifying_key:
            powers_and_material[SigningPower] = verifying_key
        if encrypting_key:
            powers_and_material[DecryptingPower] = encrypting_key

        for power_up, public_key in powers_and_material.items():
            try:
                umbral_key = PublicKey.from_bytes(public_key)
            except TypeError:
                umbral_key = public_key

            crypto_power.consume_power_up(power_up(public_key=umbral_key))

        return cls(is_me=False, crypto_power=crypto_power, *args, **kwargs)
示例#5
0
 def __init__(self,
              public_key: PublicKey = None,
              keypair: keypairs.Keypair = None):
     if keypair and public_key:
         raise ValueError(
             "Pass keypair or pubkey_bytes (or neither), but not both.")
     elif keypair:
         self.keypair = keypair
     else:
         # They didn't pass a keypair; we'll make one with the bytes or
         # Umbral PublicKey if they provided such a thing.
         if public_key:
             try:
                 public_key = public_key.as_umbral_pubkey()
             except AttributeError:
                 try:
                     public_key = PublicKey.from_bytes(public_key)
                 except TypeError:
                     public_key = public_key
             self.keypair = self._keypair_class(public_key=public_key)
         else:
             # They didn't even pass a public key.  We have no choice but to generate a keypair.
             self.keypair = self._keypair_class(
                 generate_keys_if_needed=True)
示例#6
0
    federated_only=True,
    crypto_power_ups=power_ups,
    start_learning_now=True,
    abort_on_learning_error=True,
    known_nodes=[ursula],
    save_metadata=False,
    network_middleware=RestMiddleware(),
)

print("Doctor = ", doctor)

# Let's join the policy generated by Alicia. We just need some info about it.
with open("policy-metadata.json", 'r') as f:
    policy_data = json.load(f)

policy_pubkey = PublicKey.from_bytes(
    bytes.fromhex(policy_data["policy_pubkey"]))
alices_sig_pubkey = PublicKey.from_bytes(
    bytes.fromhex(policy_data["alice_sig_pubkey"]))
label = policy_data["label"].encode()

print("The Doctor joins policy for label '{}'".format(label.decode("utf-8")))
doctor.join_policy(label, alices_sig_pubkey)

# Now that the Doctor joined the policy in the NuCypher network,
# he can retrieve encrypted data which he can decrypt with his private key.
# But first we need some encrypted data!
# Let's read the file produced by the heart monitor and unpack the MessageKits,
# which are the individual ciphertexts.
data = msgpack.load(open("heart_data.msgpack", "rb"), raw=False)
message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits'])
示例#7
0
 def encrypting_public_key(self):
     encrypting_pubkey_bytes = _read_keyfile(
         keypath=self.__root_pub_keypath, deserializer=None)
     encrypting_pubkey = PublicKey.from_bytes(encrypting_pubkey_bytes)
     return encrypting_pubkey
示例#8
0
 def signing_public_key(self):
     signature_pubkey_bytes = _read_keyfile(
         keypath=self.__signing_pub_keypath, deserializer=None)
     signature_pubkey = PublicKey.from_bytes(signature_pubkey_bytes)
     return signature_pubkey