예제 #1
0
def test_cannot_attach_cfrag_without_proof():
    """
    However, even when properly attaching keys, we can't attach the CFrag
    if it is unproven.
    """
    params = default_params()

    capsule = Capsule(params,
                      point_e=Point.gen_rand(),
                      point_v=Point.gen_rand(),
                      bn_sig=CurveBN.gen_rand())

    cfrag = CapsuleFrag(
        point_e1=Point.gen_rand(),
        point_v1=Point.gen_rand(),
        kfrag_id=os.urandom(10),
        point_precursor=Point.gen_rand(),
    )
    key_details = capsule.set_correctness_keys(
        UmbralPrivateKey.gen_key().get_pubkey(),
        UmbralPrivateKey.gen_key().get_pubkey(),
        UmbralPrivateKey.gen_key().get_pubkey())

    delegating_details, receiving_details, verifying_details = key_details

    assert all((delegating_details, receiving_details, verifying_details))

    with pytest.raises(cfrag.NoProofProvided):
        capsule.attach_cfrag(cfrag)
예제 #2
0
def test_cannot_set_different_keys():
    """
    Once a key is set on a Capsule, it can't be changed to a different key.
    """
    params = default_params()

    capsule = Capsule(params,
                      point_e=Point.gen_rand(),
                      point_v=Point.gen_rand(),
                      bn_sig=CurveBN.gen_rand())

    capsule.set_correctness_keys(
        delegating=UmbralPrivateKey.gen_key().get_pubkey(),
        receiving=UmbralPrivateKey.gen_key().get_pubkey(),
        verifying=UmbralPrivateKey.gen_key().get_pubkey())

    with pytest.raises(ValueError):
        capsule.set_correctness_keys(
            delegating=UmbralPrivateKey.gen_key().get_pubkey())

    with pytest.raises(ValueError):
        capsule.set_correctness_keys(
            receiving=UmbralPrivateKey.gen_key().get_pubkey())

    with pytest.raises(ValueError):
        capsule.set_correctness_keys(
            verifying=UmbralPrivateKey.gen_key().get_pubkey())
예제 #3
0
def test_capsule_roundtrip_1(p0, p1, b, p2, p3, p4):
    c = Capsule(params=params,
                point_e=p0,
                point_v=p1,
                bn_sig=b,
                point_e_prime=p2,
                point_v_prime=p3,
                point_noninteractive=p4)
    assert (c == Capsule.from_bytes(c.to_bytes(), params))
예제 #4
0
def test_capsule_equality():
    params = default_params()

    one_capsule = Capsule(params,
                          point_e=Point.gen_rand(),
                          point_v=Point.gen_rand(),
                          bn_sig=CurveBN.gen_rand())

    another_capsule = Capsule(params,
                              point_e=Point.gen_rand(),
                              point_v=Point.gen_rand(),
                              bn_sig=CurveBN.gen_rand())

    assert one_capsule != another_capsule
예제 #5
0
    def capsule_attach(cls, capsule: pre.Capsule, k_frags,
                       d_pk: keys.UmbralPublicKey, r_pk: keys.UmbralPublicKey,
                       v_pk: keys.UmbralPublicKey):
        capsule.set_correctness_keys(delegating=d_pk,
                                     receiving=r_pk,
                                     verifying=v_pk)

        c_frags = list()
        for kFrag in k_frags:
            c_frags.append(pre.reencrypt(kfrag=kFrag, capsule=capsule))

        for cFrag in c_frags:
            capsule.attach_cfrag(cFrag)
        return capsule.to_bytes()
예제 #6
0
def test_cannot_create_capsule_from_bogus_material(alices_keys):
    params = alices_keys[0].params

    with pytest.raises(TypeError):
        _capsule_of_questionable_parentage = Capsule(params,
                                                     point_e=Point.gen_rand(),
                                                     point_v=42,
                                                     bn_sig=CurveBN.gen_rand())

    with pytest.raises(TypeError):
        _capsule_of_questionable_parentage = Capsule(params,
                                                     point_e=Point.gen_rand(),
                                                     point_v=Point.gen_rand(),
                                                     bn_sig=42)
예제 #7
0
    def __init__(self,
                 capsule: Capsule,
                 cfrag: CapsuleFrag,
                 ursula,
                 delegating_pubkey: UmbralPublicKey = None,
                 receiving_pubkey: UmbralPublicKey = None,
                 verifying_pubkey: UmbralPublicKey = None,
                 ) -> None:
        self.capsule = capsule
        self.cfrag = cfrag
        self.ursula = ursula

        keys = capsule.get_correctness_keys()
        key_types = ("delegating", "receiving", "verifying")
        if all(keys[key_type] for key_type in key_types):
            self.delegating_pubkey = keys["delegating"]
            self.receiving_pubkey = keys["receiving"]
            self.verifying_pubkey = keys["verifying"]
        elif all((delegating_pubkey, receiving_pubkey, verifying_pubkey)):
            self.delegating_pubkey = delegating_pubkey
            self.receiving_pubkey = receiving_pubkey
            self.verifying_pubkey = verifying_pubkey
        else:
            raise ValueError("All correctness keys are required to compute evidence.  "
                             "Either pass them as arguments or in the capsule.")
예제 #8
0
def test_capsule_equality():
    one_capsule = Capsule(point_e=Point.gen_rand(),
                          point_v=Point.gen_rand(),
                          bn_sig=CurveBN.gen_rand())

    another_capsule = Capsule(point_e=Point.gen_rand(),
                              point_v=Point.gen_rand(),
                              bn_sig=CurveBN.gen_rand())

    assert one_capsule != another_capsule

    activated_capsule = Capsule(point_e_prime=Point.gen_rand(),
                                point_v_prime=Point.gen_rand(),
                                point_noninteractive=Point.gen_rand())

    assert activated_capsule != one_capsule
예제 #9
0
파일: models.py 프로젝트: mallek/nucypher
    def from_rest_payload(cls, arrangement_id, rest_payload):

        # TODO: Use JSON instead? This is a mess.
        payload_splitter = BytestringSplitter(Signature) + key_splitter
        signature, bob_pubkey_sig, remainder = payload_splitter(
            rest_payload, msgpack_remainder=True)

        receipt_bytes, *remainder = remainder
        packed_capsules, packed_signatures, *remainder = remainder
        alice_address, alice_address_signature = remainder
        alice_address_signature = Signature.from_bytes(alice_address_signature)
        if not alice_address_signature.verify(alice_address, bob_pubkey_sig):
            raise cls.NotFromBob()

        capsules, capsule_signatures = list(), list()
        for capsule_bytes, capsule_signature in zip(
                msgpack.loads(packed_capsules),
                msgpack.loads(packed_signatures)):
            capsules.append(
                Capsule.from_bytes(capsule_bytes, params=default_params()))
            capsule_signature = Signature.from_bytes(capsule_signature)
            capsule_signatures.append(capsule_signature)
            if not capsule_signature.verify(capsule_bytes, bob_pubkey_sig):
                raise cls.NotFromBob()

        verified = signature.verify(receipt_bytes, bob_pubkey_sig)
        if not verified:
            raise cls.NotFromBob()
        bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig})
        return cls(bob, arrangement_id, capsules, capsule_signatures,
                   alice_address, alice_address_signature, receipt_bytes,
                   signature)
예제 #10
0
    def decrypt_by_sk(cls, sk: keys.UmbralPrivateKey,
                      d_pk: keys.UmbralPublicKey, v_pk: keys.UmbralPublicKey,
                      encrypt_text: bytes, capsule: pre.Capsule, k_frags):
        capsule.set_correctness_keys(delegating=d_pk,
                                     receiving=sk.get_pubkey(),
                                     verifying=v_pk)
        c_frags = list()
        for kFrag in k_frags:
            c_frags.append(pre.reencrypt(kfrag=kFrag, capsule=capsule))
        for cfrag in c_frags:
            capsule.attach_cfrag(cfrag)

        decrypt_text = pre.decrypt(ciphertext=encrypt_text,
                                   capsule=capsule,
                                   decrypting_key=sk)
        return decrypt_text.decode("utf-8")
def test_capsule_equality():
    one_capsule = Capsule(point_eph_e=Point.gen_rand(),
                          point_eph_v=Point.gen_rand(),
                          bn_sig=BigNum.gen_rand())

    another_capsule = Capsule(point_eph_e=Point.gen_rand(),
                              point_eph_v=Point.gen_rand(),
                              bn_sig=BigNum.gen_rand())

    assert one_capsule != another_capsule

    activated_capsule = Capsule(e_prime=Point.gen_rand(),
                                v_prime=Point.gen_rand(),
                                noninteractive_point=Point.gen_rand())

    assert activated_capsule != one_capsule
예제 #12
0
def test_capsule_creation(alices_keys):
    with pytest.raises(TypeError):
        rare_capsule = Capsule()  # Alice cannot make a capsule this way.

    # Some users may create capsules their own way.
    custom_capsule = Capsule(point_e=Point.gen_rand(),
                             point_v=Point.gen_rand(),
                             bn_sig=CurveBN.gen_rand())

    assert isinstance(custom_capsule, Capsule)

    # Typical Alice, constructing a typical capsule
    _, alices_public_key = alices_keys
    plaintext = b'peace at dawn'
    ciphertext, typical_capsule = pre.encrypt(alices_public_key, plaintext)

    assert isinstance(typical_capsule, Capsule)
예제 #13
0
def test_cannot_attach_cfrag_without_keys():
    """
    We need the proper keys to verify the correctness of CFrags
    in order to attach them to a Capsule.
    """
    capsule = Capsule(point_e=Point.gen_rand(),
                      point_v=Point.gen_rand(),
                      bn_sig=CurveBN.gen_rand())

    cfrag = CapsuleFrag(
        point_e1=Point.gen_rand(),
        point_v1=Point.gen_rand(),
        kfrag_id=os.urandom(10),
        point_noninteractive=Point.gen_rand(),
        point_xcoord=Point.gen_rand(),
    )
    with pytest.raises(TypeError):
        capsule.attach_cfrag(cfrag)
예제 #14
0
def test_bad_capsule_fails_reencryption(alices_keys):
    priv_key_alice, pub_key_alice = alices_keys

    kfrags = pre.split_rekey(priv_key_alice, pub_key_alice, 1, 2)

    bollocks_capsule = Capsule(point_e=Point.gen_rand(),
                               point_v=Point.gen_rand(),
                               bn_sig=CurveBN.gen_rand())

    with pytest.raises(Capsule.NotValid):
        pre.reencrypt(kfrags[0], bollocks_capsule)
예제 #15
0
def test_bad_capsule_fails_reencryption(kfrags):
    params = default_params()

    bollocks_capsule = Capsule(params,
                               point_e=Point.gen_rand(),
                               point_v=Point.gen_rand(),
                               bn_sig=CurveBN.gen_rand())

    for kfrag in kfrags:
        with pytest.raises(Capsule.NotValid):
            pre.reencrypt(kfrag, bollocks_capsule)
예제 #16
0
 def from_rest_payload(cls, kfrag_hrac, rest_payload):
     payload_splitter = BytestringSplitter(Signature) + key_splitter
     signature, bob_pubkey_sig, (receipt_bytes,
                                 packed_capsules) = payload_splitter(
                                     rest_payload, msgpack_remainder=True)
     capsules = [
         Capsule.from_bytes(p) for p in msgpack.loads(packed_capsules)
     ]
     verified = signature.verify(receipt_bytes, bob_pubkey_sig)
     if not verified:
         raise ValueError("This doesn't appear to be from Bob.")
     bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig})
     return cls(bob, kfrag_hrac, capsules, receipt_bytes, signature)
예제 #17
0
def test_capsule_serialization(capsule: Capsule):
    params = capsule.params
    capsule_bytes = capsule.to_bytes()
    capsule_bytes_casted = bytes(capsule)
    assert capsule_bytes == capsule_bytes_casted

    # A Capsule can be represented as the 98 total bytes of two Points (33 each) and a CurveBN (32).
    assert len(capsule_bytes) == Capsule.expected_bytes_length()

    new_capsule = Capsule.from_bytes(capsule_bytes, params)

    # Three ways to think about equality.
    # First, the public approach for the Capsule.  Simply:
    assert new_capsule == capsule

    # Second, we show that the original components (which is all we have here since we haven't activated) are the same:
    assert new_capsule.components() == capsule.components()

    # Third, we can directly compare the private original component attributes
    # (though this is not a supported approach):
    assert new_capsule.point_e == capsule.point_e
    assert new_capsule.point_v == capsule.point_v
    assert new_capsule.bn_sig == capsule.bn_sig
예제 #18
0
def decrypt():
    api = ipfsapi.connect('127.0.0.1', 5001)
    res = {}
    cfrags = list()
    if request.headers['Content-Type'] == 'application/json':
        account = request.json['account']
        ciphertexthex = request.json['ciphertext']
        b_ciphertext = bytes.fromhex(ciphertexthex)
        decryptkey = request.json['decryptkey']
        b_decryptkey = bytes.fromhex(decryptkey)
        deckey = UmbralPrivateKey.from_bytes(b_decryptkey)
        capsuleaddr = request.json['capsule']
        b_capsule_all = api.cat(capsuleaddr)
        splitarr1 = b_capsule_all.split(b'ZAtech')
        b_basic_capsule = splitarr1[0]
        capsule = Capsule.from_bytes(b_basic_capsule,
                                     UmbralParameters(Curve(714)))
        print("0")
        correctness_keys = splitarr1[1]
        splitarr2 = correctness_keys.split(b'ZBtech')
        delegating = UmbralPublicKey.from_bytes(splitarr2[0])
        receiving = UmbralPublicKey.from_bytes(splitarr2[1])
        verifying = UmbralPublicKey.from_bytes(splitarr2[2])

        # 用带入的参数capsule_all的各种byte,重现绑定correctness keys的capsule.
        capsule.set_correctness_keys(delegating=delegating,
                                     receiving=receiving,
                                     verifying=verifying)
        print("1")

        b_cfrag_all = splitarr1[2].split(b'ZCtech')
        for b_cfrag in b_cfrag_all:
            cfrags.append(CapsuleFrag.from_bytes(b_cfrag))
        for cfrag in cfrags:
            capsule.attach_cfrag(cfrag)
        print("2")
        print(capsule)
        print(capsule.get_correctness_keys())
        print(cfrags)
        cleartext = pre.decrypt(ciphertext=b_ciphertext,
                                capsule=capsule,
                                decrypting_key=deckey)
        print("3")

        res = {"cleartext": cleartext.decode("utf-8")}
        print("\nbob_cleartext: ")
        print(cleartext)
        return jsonify(res), {'Content-Type': 'application/json'}
    return
예제 #19
0
def test_bad_capsule_fails_reencryption(alices_keys, bobs_keys):
    delegating_privkey, _signing_privkey = alices_keys
    signer_alice = Signer(_signing_privkey)

    _receiving_privkey, receiving_pubkey = bobs_keys

    kfrags = pre.split_rekey(delegating_privkey, signer_alice,
                             receiving_pubkey, 1, 2)

    bollocks_capsule = Capsule(point_e=Point.gen_rand(),
                               point_v=Point.gen_rand(),
                               bn_sig=CurveBN.gen_rand())

    with pytest.raises(Capsule.NotValid):
        pre.reencrypt(kfrags[0], bollocks_capsule)
예제 #20
0
    def from_rest_payload(cls, arrangement_id, rest_payload):
        payload_splitter = BytestringSplitter(Signature) + key_splitter
        signature, bob_pubkey_sig, \
            (receipt_bytes, packed_capsules, packed_signatures) = payload_splitter(rest_payload,
                                                                                   msgpack_remainder=True)
        capsules, capsule_signatures = list(), list()
        for capsule_bytes, signed_capsule in zip(msgpack.loads(packed_capsules), msgpack.loads(packed_signatures)):
            capsules.append(Capsule.from_bytes(capsule_bytes, params=default_params()))
            signed_capsule = Signature.from_bytes(signed_capsule)
            capsule_signatures.append(signed_capsule)
            if not signed_capsule.verify(capsule_bytes, bob_pubkey_sig):
                raise ValueError("This doesn't appear to be from Bob.")

        verified = signature.verify(receipt_bytes, bob_pubkey_sig)
        if not verified:
            raise ValueError("This doesn't appear to be from Bob.")
        bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig})
        return cls(bob, arrangement_id, capsules, capsule_signatures, receipt_bytes, signature)
예제 #21
0
def de_route():
    if not request.json:
        abort(400)
    capsule_raw = request.json['capsule']
    capsule = Capsule.from_bytes(bytes.fromhex(capsule_raw), params)

    alices_public_key = getUmbralPublicFromHex(
        request.json['alices_public_key'])
    alices_verifying_key = getUmbralPublicFromHex(
        request.json['alices_verifying_key'])  # ? maybe without 03
    ciphertext = bytes.fromhex(request.json['ciphertext'])
    bobs_private_key = getUmbralPrivateFromHex(
        request.json['bobs_private_key'])
    # kfrags
    serialized_kfrags = request.json['kfrags']
    kfrags = []
    for skfrag in serialized_kfrags:
        kfrags.append(KFrag.from_bytes(bytes.fromhex(skfrag)))

    responce = de(capsule, alices_public_key, alices_verifying_key, ciphertext,
                  bobs_private_key, kfrags)
    print(responce)
    return responce, 200
예제 #22
0
def test_capsule_roundtrip_0(p0, p1, b):
    c = Capsule(params=params, point_e=p0, point_v=p1, bn_sig=b)
    assert(c == Capsule.from_bytes(c.to_bytes(), params=params))
예제 #23
0
def fetch():
    api = ipfsapi.connect('127.0.0.1', 5001)
    if request.headers['Content-Type'] == 'application/json':
        account = request.json['account']
        # 所有的传入参数都是hex key
        capsuleaddr = request.json['capsule']
        b_capsule_all = api.cat(capsuleaddr)
        splitarr1 = b_capsule_all.split(b'ZAtech')
        b_basic_capsule = splitarr1[0]
        capsule = Capsule.from_bytes(b_basic_capsule,
                                     UmbralParameters(Curve(714)))
        correctness_keys = splitarr1[1]
        splitarr2 = correctness_keys.split(b'ZBtech')
        delegating = UmbralPublicKey.from_bytes(splitarr2[0])
        receiving = UmbralPublicKey.from_bytes(splitarr2[1])
        verifying = UmbralPublicKey.from_bytes(splitarr2[2])
        # print(splitarr1[0])
        # print(splitarr1[1])
        # print(splitarr2[0])
        # print(splitarr2[1])
        # print(splitarr2[2])
        print(delegating)
        print(receiving)
        print(verifying)
        caddrs = request.json['addresses']

        # 用带入的参数capsule_all的各种byte,重现绑定correctness keys的capsule.
        capsule.set_correctness_keys(delegating=delegating,
                                     receiving=receiving,
                                     verifying=verifying)
        print(capsule.get_correctness_keys())

        cfrags = list()
        all_bytes = b''
        index = 0
        for addr in caddrs:
            index += 1
            b_cfrag = api.cat(addr)
            all_bytes += b_cfrag
            if index < len(caddrs):
                all_bytes += b'ZCtech'
            cfrags.append(CapsuleFrag.from_bytes(api.cat(addr)))

        for cfrag in cfrags:
            capsule.attach_cfrag(cfrag)

        # 再将append的内容写入capsule,然后就可以将解密单独拎出来。

        b_capsule_all += b'ZAtech' + all_bytes
        savedcapaddr = api.add_bytes(b_capsule_all)

        # splitarr = b_capsule_all.split(b'ZAtech')
        # splitarrmiddle = splitarr[1].split(b'ZBtech')
        # splitarrlast = splitarr[2].split(b'ZCtech')
        # print(len(cfrags))
        # for s in splitarrmiddle:
        #     print(s)
        # print(len(splitarrlast))
        # for s in splitarrlast:
        #     print(s)

        res = {"capsule": savedcapaddr}
        return jsonify(res), {'Content-Type': 'application/json'}

    return
예제 #24
0
def reencrypt():
    api = ipfsapi.connect('127.0.0.1', 5001)
    addrs = list()
    caddrs = list()
    res = {}
    if request.headers['Content-Type'] == 'application/json':
        account = request.json['account']
        # 所有的传入参数都是hex key
        threshold = request.json['threshold']
        capsulehex = request.json['capsule']
        b_capsule = api.cat(capsulehex)
        capsule = Capsule.from_bytes(b_capsule, UmbralParameters(Curve(714)))
        addrs = request.json['addresses']

        delegatinghex = request.json['delegating']
        b_delegating = bytes.fromhex(delegatinghex)
        delegating = UmbralPublicKey.from_bytes(b_delegating)
        receivinghex = request.json['receiving']
        b_receiving = bytes.fromhex(receivinghex)
        receiving = UmbralPublicKey.from_bytes(b_receiving)
        verifyinghex = request.json['verifying']
        b_verifying = bytes.fromhex(verifyinghex)
        verifying = UmbralPublicKey.from_bytes(b_verifying)
        if threshold > len(addrs):
            return "Not enough addresses."

        capsule.set_correctness_keys(delegating=delegating,
                                     receiving=receiving,
                                     verifying=verifying)

        cfrags = list()  # Receiver's cfrag collection
        # each kfrag is a rk segment
        for addr in addrs:
            rkseg = KFrag.from_bytes(api.cat(addr))
            # cfrag = pre.reencrypt(kfrag=kfrag, capsule=capsule)
            cfrag = pre.reencrypt(kfrag=rkseg, capsule=capsule)
            cfrags.append(cfrag)  # Receiver's collects a cfrag

        for cfrag in cfrags:
            caddrs.append(api.add_bytes(cfrag.to_bytes()))
        savedcap = capsule.to_bytes_all()
        # savedcap包括三块,basic为capsule,correctness为set的key,cfrag是append上去的东西,此时还为空
        print(type(savedcap))
        print(type(savedcap['basic']))

        print(savedcap['correctness'])
        delegating_key = savedcap['correctness']['delegating']
        receiving_key = savedcap['correctness']['receiving']
        verifying_key = savedcap['correctness']['verifying']

        b_delegating_key = delegating_key.to_bytes()
        b_receiving_key = receiving_key.to_bytes()
        b_verifying_key = verifying_key.to_bytes()

        print(b_delegating_key)
        print(b_receiving_key)
        print(b_verifying_key)

        sendbytes = savedcap[
            'basic'] + b'ZAtech' + b_delegating_key + b'ZBtech' + b_receiving_key + b'ZBtech' + b_verifying_key

        print(sendbytes)

        savedcapaddr = api.add_bytes(sendbytes)

        res = {"caddrs": caddrs, "capsule": savedcapaddr}
        return jsonify(res), {'Content-Type': 'application/json'}
    return