示例#1
0
    def key_create(self):
        if not os.path.exists("key_pair.pkl"):
            key_pair={}
            self.key=fernet.Fernet.generate_key()#对称加密密钥
            #创建节点非对称加密的私钥与公钥
            self.pri_key=keys.UmbralPrivateKey.gen_key()
            self.pub_key=self.pri_key.get_pubkey()
            #创造数字签名用私钥与公钥
            self.signing_key = keys.UmbralPrivateKey.gen_key()
            self.verifying_key=self.signing_key.get_pubkey()
            self.signer = signing.Signer(self.signing_key)
            #保存,二值化处理
            key_pair["key"]=self.key
            key_pair["pri_key"]=self.pri_key.to_bytes()
            key_pair["pub_key"]=self.pub_key.to_bytes()
            key_pair["signing_key"]=self.signing_key.to_bytes()
            key_pair["verifying_key"]=self.verifying_key.to_bytes()
            with open("key_pair.pkl","wb") as f:
                pickle.dump(key_pair,f)
                print("the key pair has been saved")

        else:
            with open("key_pair.pkl","rb") as f:
                key_pair=pickle.load(f)
                pub_key=keys.UmbralPublicKey.from_bytes(key_pair["pub_key"])
                verifying_key=keys.UmbralPublicKey.from_bytes(key_pair["verifying_key"])
                pri_key=keys.UmbralPrivateKey.from_bytes(key_pair["pri_key"])
                signing_key=keys.UmbralPrivateKey.from_bytes(key_pair["signing_key"])
                self.key=key_pair["key"]
                self.pri_key=pri_key
                self.pub_key=pub_key
                self.signing_key=signing_key
                self.verifying_key=verifying_key
                self.signer=signing.Signer(self.signing_key)
                print("the key pair loads success")
示例#2
0
文件: launcher.py 项目: VanyLaw/PoC
    def get(self):
        sk_filename = "pk1"
        sk = keys.UmbralPrivateKey.gen_key()
        open("data/pk/" + sk_filename, "w").write(sk.to_bytes().hex())
        vk = sk.get_pubkey()
        user_id = vk.to_bytes().hex()
        timestamp = time.time()
        sk_sign = signing.Signer(sk)
        signature = sk_sign(str(timestamp).encode("utf8"))

        known_addresses_list = list(ControlHandler.known_addresses)
        addr = random.choice(known_addresses_list)
        http_client = tornado.httpclient.AsyncHTTPClient()
        # print(len(vk.to_bytes().hex()), vk.to_bytes().hex())
        # print(len(bytes(signature).hex()), bytes(signature).hex())
        url = "http://%s:%s/user?user_id=%s&signature=%s&timestamp=%s" % (
            tuple(addr) + (user_id, bytes(signature).hex(), str(timestamp)))
        # print(url)
        try:
            response = yield http_client.fetch(
                url)  #, method="POST", body=tornado.escape.json_encode(data)
        except Exception as e:
            print("Error: %s" % e)

        self.finish({"user_id": user_id})
示例#3
0
def grant_access():
    if request.method == 'POST':
        # Get the data from the request payload and convert them to bytes
        bobPubKey = string_to_bytes(request.form["bobPubKey"])
        bobPubKey = keys.UmbralPublicKey.from_bytes(bobPubKey)
        alicePrivKey = string_to_bytes(request.form["alicePrivKey"])
        alicePrivKey = keys.UmbralPrivateKey.from_bytes(alicePrivKey)
        alicePubKey = alicePrivKey.get_pubkey()

        #generate the signing key
        alices_signing_key = keys.UmbralPrivateKey.gen_key()
        alices_verifying_key = alices_signing_key.get_pubkey()
        alices_signer = signing.Signer(private_key=alices_signing_key)

        # Generating kfrags
        global kfrags
        kfrags = pre.generate_kfrags(delegating_privkey=alicePrivKey,
                                     signer=alices_signer,
                                     receiving_pubkey=bobPubKey,
                                     threshold=10,
                                     N=20)

        # Storing the kfrags on the bob's side
        dataToBeStoredBob = {
            "alice_verifying_key":
            bytes_to_string(alices_verifying_key.to_bytes()),
            "alicePubKey": bytes_to_string(alicePubKey.to_bytes())
        }

        with open('hospital.json', 'w') as outfile:
            json.dump(dataToBeStoredBob, outfile, cls=SetEncoder)

    return render_template('grant.html')
def gen_rencryption_key():
    if request.content_type.lower() != "application/json":
        abort(415)

    data = request.get_json()

    if "delegatorPrivateKey" in data and "delegatorSigningKey" in data and "receiverPublicKey" in data:
        try:
            start = time.perf_counter()
            delegatorPrivKey = keys.UmbralPrivateKey.from_bytes(
                bytes.fromhex(data["delegatorPrivateKey"]))
            delegatorSignKey = keys.UmbralPrivateKey.from_bytes(
                bytes.fromhex(data["delegatorSigningKey"]))
            receiverPublicKey = keys.UmbralPublicKey.from_hex(
                data["receiverPublicKey"])
            signer = signing.Signer(private_key=delegatorSignKey)

            [kfrag] = pre.generate_kfrags(delegating_privkey=delegatorPrivKey,
                                          signer=signer,
                                          receiving_pubkey=receiverPublicKey,
                                          threshold=1,
                                          N=1)
            end = time.perf_counter()

            time_stats_endpoints["gen_renc_key"].append(end - start)

            return {"status": "ok", "reencKey": kfrag.to_bytes().hex()}
        except Exception as e:
            return {"status": "error", "error": str(e)}

    abort(400)
示例#5
0
def encrypt():
    if not request.json:
        abort(400)

    bob_public_key = request.json['recipient']
    pop_correct_public_key_hex = "03" + bob_public_key[-64:]
    print(pop_correct_public_key_hex)
    signedtext = request.json['data']

    alices_signing_key = keys.UmbralPrivateKey.gen_key()
    alices_verifying_key = alices_signing_key.get_pubkey()
    alices_signer = signing.Signer(private_key=alices_signing_key)

    #signedText

    bob = keys.UmbralPublicKey.from_bytes(
        bytes.fromhex(pop_correct_public_key_hex))
    ciphertext, capsule = pre.encrypt(bob, str.encode(signedtext))
    #grants access to Bob

    # kfrags = pre.generate_kfrags(delegating_privkey=alices_signing_key,
    # signer=alices_signer,
    # receiving_pubkey=bob,
    # threshold=10,
    # N=20)
    #, "capsule":capsule
    return jsonify(ciphertext=ciphertext.hex(),
                   capsule=capsule.to_bytes().hex()), 200
示例#6
0
def setup(alices_private_key, bobs_private_key, n, m):
    #################
    # Generate Umbral keys for Alice.
    ################# []
    # alices_private_key = keys.UmbralPrivateKey.gen_key()
    alices_public_key = alices_private_key.get_pubkey()
    print("alices_private_key", alices_private_key)

    alices_signing_key = keys.UmbralPrivateKey.gen_key()
    alices_verifying_key = alices_signing_key.get_pubkey()
    # assert alices_public_key == alices_verifying_key # it souldn't
    alices_signer = signing.Signer(private_key=alices_signing_key)

    # Generate Umbral keys for Bob.
    ################# []
    # bobs_private_key = keys.UmbralPrivateKey.gen_key()
    bobs_public_key = bobs_private_key.get_pubkey()
    print("bobs_public_key", bobs_public_key)

    # Alice generates "M of N" re-encryption key fragments (or "KFrags") for Bob.
    # In this example, 10 out of 20.
    kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key,
                                 signer=alices_signer,
                                 receiving_pubkey=bobs_public_key,
                                 threshold=m,
                                 N=n)

    return alices_public_key, alices_signing_key, alices_verifying_key, bobs_public_key, kfrags
示例#7
0
def generate_secret_key():
    alices_private_key = keys.UmbralPrivateKey.gen_key()
    alices_public_key = alices_private_key.get_pubkey()

    alices_signing_key = keys.UmbralPrivateKey.gen_key()
    alices_verifying_key = alices_signing_key.get_pubkey()
    alices_signer = signing.Signer(private_key=alices_signing_key)

    # Generate Umbral keys for Bob.
    bobs_private_key = keys.UmbralPrivateKey.gen_key()
    bobs_public_key = bobs_private_key.get_pubkey()
    plaintext = b'Proxy Re-Encryption is cool!'
    ciphertext, capsule = pre.encrypt(alices_public_key, plaintext)

    # Decrypt data with Alice's private key.
    cleartext = pre.decrypt(ciphertext=ciphertext,
                            capsule=capsule,
                            decrypting_key=alices_private_key)
    kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key,
                             signer=alices_signer,
                             receiving_pubkey=bobs_public_key,
                             threshold=10,
                             N=20)
    return jsonify(
        {
            "encrypted_result": f'{kfrags}'
        } 
    )
示例#8
0
文件: dashboard.py 项目: VanyLaw/PoC
    def get(self):
        sk_filename = "pk1"
        sk = keys.UmbralPrivateKey.from_bytes(
            bytes.fromhex(open("data/pk/" + sk_filename).read()))
        vk = sk.get_pubkey()
        user_id = vk.to_bytes().hex()
        # sender_binary = bin(int(vk.to_bytes().hex(), 16))#[2:].zfill(768)
        timestamp = time.time()
        sk_sign = signing.Signer(sk)
        signature = sk_sign(str(timestamp).encode("utf8"))
        assert signature.verify(str(timestamp).encode("utf8"), vk)

        known_addresses_list = list(ControlHandler.known_addresses)
        addr = random.choice(known_addresses_list)
        http_client = tornado.httpclient.AsyncHTTPClient()
        print(len(vk.to_bytes().hex()), vk.to_bytes().hex())
        # print(len(bin(int(vk.to_bytes().hex(), 16))), bin(int(vk.to_bytes().hex(), 16)))
        print(len(bytes(signature).hex()), bytes(signature).hex())
        url = "http://%s:%s/user?user_id=%s&timestamp=%s&signature=%s" % (
            tuple(addr) + (user_id, str(timestamp), bytes(signature).hex()))
        # print(url)
        try:
            response = yield http_client.fetch(
                url)  #, method="POST", body=tornado.escape.json_encode(data)
        except Exception as e:
            print("Error: %s" % e)

        self.finish(tornado.escape.json_decode(response.body))
示例#9
0
文件: dashboard.py 项目: VanyLaw/PoC
    def get(self):
        sk_filename = "pk1"
        sk = keys.UmbralPrivateKey.gen_key()
        open("data/pk/" + sk_filename, "w").write(sk.to_bytes().hex())
        vk = sk.get_pubkey()
        user_id = vk.to_bytes().hex()
        timestamp = str(time.time())
        sk_sign = signing.Signer(sk)
        signature = sk_sign(timestamp.encode("utf8"))

        content = b"{}"
        ciphertext, capsule = pre.encrypt(vk, content)
        folder_size = "0"
        block_size = len(ciphertext)
        folder_hash = hashlib.sha1(ciphertext).hexdigest()
        folder_hash_binary = bin(int(folder_hash, 16))[2:].zfill(32 * 4)
        addr, groupid = yield get_group(folder_hash_binary)
        print("ciphertext", len(ciphertext), "capsule",
              capsule.to_bytes().hex())

        http_client = tornado.httpclient.AsyncHTTPClient()
        url = "http://%s:%s/user?user_id=%s&folder_hash=%s&block_size=%s&folder_size=%s&groupid=%s&capsule=%s&timestamp=%s&signature=%s" \
                % (tuple(addr)+(user_id, folder_hash, block_size, folder_size, groupid, capsule.to_bytes().hex(), timestamp, bytes(signature).hex()))
        try:
            response = yield http_client.fetch(url,
                                               method="POST",
                                               body=ciphertext)
        except Exception as e:
            print("Error: %s" % e)

        self.finish({"user_id": user_id})
示例#10
0
def get_signer_keys ():
    alices_private_key = keys.UmbralPrivateKey.gen_key()
    alices_public_key = alices_private_key.get_pubkey()
    alices_signing_key = keys.UmbralPrivateKey.gen_key()
    alices_verifying_key = alices_signing_key.get_pubkey()
    alices_signer = signing.Signer(private_key=alices_signing_key)
    newkeys = {"privateSigningKey": alices_signing_key, "publicSigningKey": alices_verifying_key, "signer": alices_signer}
    # print (newkeys) 
    with open("python/proxy/23.jpg", "rb") as imageFile:
        f = imageFile.read()
        plaintext = bytes(f)
    # print("imgStart")
    # print(b)
    # print("imgEnd")

    # plaintext = b'Proxy Re-encryption is cool!'
    # print("@@@@")
    # print(plaintext)
    ciphertext, capsule = pre.encrypt(alices_public_key, plaintext)
    # print(ciphertext)
    print(capsule)
    bob_capsule = capsule
    bobs_private_key = keys.UmbralPrivateKey.gen_key()
    bobs_public_key = bobs_private_key.get_pubkey()
    kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key,
                                signer=alices_signer,
                                receiving_pubkey=bobs_public_key,
                                threshold=10,
                                N=20)
    print(kfrags)
    bob_capsule.set_correctness_keys(delegating=alices_public_key,
                                 receiving=bobs_public_key,
                                 verifying=alices_verifying_key)
示例#11
0
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.connected_clients = []
        self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # TODO
        set_default_curve()
        self.alices_private_key = keys.UmbralPrivateKey.from_bytes(
            b'\x86(\xb4Av\xa7\xf8\x1a\x16\x08\xc0K3\xa8\x1a;"i\xa8\x13Q\xc4s\xe5\x19\xef\x86@\x011\xf7\xfd'
        )
        self.alices_public_key = keys.UmbralPublicKey.from_bytes(
            b'\x03\xb6\x81\xba\x8e\xcb\x08e\x7f(\x04\xe3\xff\xbe\xc6UA\xa0\xfe5\x1c\xb2\xe0\xf0\xf7;\xd1D}NHo\xf7'
        )

        self.alices_signing_key = keys.UmbralPrivateKey.from_bytes(
            b'Q:5|\x01^=\xd6D\xbd\xed\xbb\x8f\xef\xc9\x04\xed2g}\xf3Yn\xf4\xb2\xfdZ\x03\x16\xceM\x94'
        )
        self.alices_verifying_key = keys.UmbralPublicKey.from_bytes(
            b'\x03Yn\x9dx\xa7\x1c\xd1\xad\xe5\x80\xc9[\xe8^\xae\x81\x95\xaaQ\xadi\x9d\x83\x91\x18}\xc2\x85\xe3\x1em\xd0'
        )
        self.alices_signer = signing.Signer(
            private_key=self.alices_signing_key)

        try:
            self._db_connect()
        except BaseException:
            log_info("Unable to connect database")
示例#12
0
文件: nucy.py 项目: crazoes/drm
    def __init__(self):
        self.alices_private_key = keys.UmbralPrivateKey.gen_key()
        self.alices_public_key = self.alices_private_key.get_pubkey()

        self.alices_signing_key = keys.UmbralPrivateKey.gen_key()
        self.alices_verifying_key = self.alices_signing_key.get_pubkey()
        self.alices_signer = signing.Signer(
            private_key=self.alices_signing_key)
示例#13
0
文件: dashboard.py 项目: VanyLaw/PoC
    def get(self):
        USER_NO = 4
        count = int(self.get_argument("n", "1"))
        for i in range(count):
            user_nos = list(range(USER_NO))
            i = random.choice(user_nos)
            sender_filename = "pk" + str(i)
            sender_sk = keys.UmbralPrivateKey.from_bytes(
                bytes.fromhex(open("data/pk/" + sender_filename).read()))
            sender_vk = sender_sk.get_pubkey()
            sender = sender_vk.to_bytes().hex()

            user_nos.remove(i)
            j = random.choice(user_nos)
            receiver_filename = "pk" + str(j)
            receiver_sk = keys.UmbralPrivateKey.from_bytes(
                bytes.fromhex(open("data/pk/" + receiver_filename).read()))
            amount = random.randint(1, 20)
            receiver_vk = receiver_sk.get_pubkey()
            receiver = receiver_vk.to_bytes().hex()

            txid = uuid.uuid4().hex
            timestamp = int(time.time())
            transaction = {
                "txid": txid,
                "sender": sender,
                "receiver": receiver,
                "timestamp": timestamp,
                "amount": amount
            }
            # print(transaction)
            sender_sign = signing.Signer(sender_sk)
            signature = sender_sign(str(timestamp).encode("utf8"))
            data = {
                "transaction": transaction,
                "signature": bytes(signature).hex()
            }

            assert signature.verify(str(timestamp).encode("utf8"), sender_vk)

            known_addresses_list = list(ControlHandler.known_addresses)
            addr = random.choice(known_addresses_list)

            self.write("%s %s\n" % addr)
            http_client = tornado.httpclient.AsyncHTTPClient()
            try:
                response = yield http_client.fetch(
                    "http://%s:%s/new_tx" % tuple(addr),
                    method="POST",
                    body=tornado.escape.json_encode(data))
            except Exception as e:
                print("Error: %s" % e)
            # result = tornado.escape.json_decode(response.body)
            # branches = result["available_branches"]

            self.write("%s\n" % response.body)
            # self.write("new tx %s\n" % txid)
        self.finish()
示例#14
0
 def __init__(self):  #构造函数
     self.verify_key, self.__sign_key = ecdas.generate_key()
     self.__recrypt_private_key = keys.UmbralPrivateKey.gen_key()
     self.recrypt_public_key = self.__recrypt_private_key.get_pubkey()
     self.__reencrypto_signing_key = keys.UmbralPrivateKey.gen_key()
     self.reencrypto_verifying_key = self.__reencrypto_signing_key.get_pubkey(
     )
     self.__reencrypto_signer = signing.Signer(
         private_key=self.__reencrypto_signing_key)
示例#15
0
 def generate_k_flags(
         cls, sk: keys.UmbralPrivateKey,
         escrow_pk: keys.UmbralPublicKey) -> (List[pre.KFrag], str):
     proxy_signing_key = keys.UmbralPrivateKey.gen_key()
     proxy_public_key = proxy_signing_key.get_pubkey()
     signer = signing.Signer(private_key=proxy_signing_key)
     k_frags = pre.generate_kfrags(delegating_privkey=sk,
                                   signer=signer,
                                   receiving_pubkey=escrow_pk,
                                   threshold=10,
                                   N=20)
     k_frags = random.sample(k_frags, 10)
     return k_frags, proxy_public_key.to_bytes()
 def share(self, keyName, path, publicKeyFileName):
     key = self.contract.call().keys(keyName)
     keyExist = key[4]
     if keyExist:
         try:
             with open(path + '/' + publicKeyFileName + '.k', 'rb') as publicKeyFile:
                 publicKeyBytes = publicKeyFile.read()
         except Exception as e:
             print(e)
         else:
             try:
                 publicKey = keys.UmbralPublicKey.from_bytes(publicKeyBytes)
                 signingPrivateKey = keys.UmbralPrivateKey.gen_key()
                 signer = signing.Signer(private_key = signingPrivateKey)
                 kfrags = pre.generate_kfrags(
                     delegating_privkey = self.privateKey,
                     signer = signer,
                     receiving_pubkey = publicKey,
                     threshold = 1,
                     N = 1
                 )
                 directory = path + '/' + publicKeyFileName + '/'
                 if not os.path.exists(directory):
                     os.makedirs(directory)
                 curveVar = umbral.config.default_curve()
                 paramsVar = params.UmbralParameters(curveVar)
                 capsule = pre.Capsule.from_bytes(key[1], paramsVar)
                 signingPublicKey = signingPrivateKey.get_pubkey()
                 capsule.set_correctness_keys(
                     delegating = self.publicKey,
                     receiving = publicKey,
                     verifying = signingPublicKey
                 )
                 for kfrag in kfrags:
                     cfrag = pre.reencrypt(
                         kfrag = kfrag,
                         capsule = capsule
                     )
                     cfrag = cfrag.to_bytes()
                 keyName = keyName.decode('utf-8')
                 with open(directory + keyName + '.f', 'wb') as cfragFile:
                     cfragFile.write(cfrag)
                 signingPublicKeyBytes = signingPublicKey.to_bytes()
                 with open(directory + keyName + '.s', 'wb') as signatureFile:
                     signatureFile.write(signingPublicKeyBytes)
             except Exception as e:
                 print(e)
             else:
                 print('Done')
     else:
         print('Key is not exist')
示例#17
0
    def key_create(self):

        #create the key-config file or load the key-config file
        #the symmetrical key will be temporarily created when file upload the IPFS
        if not os.path.exists("key_pair.pkl"):
            key_pair = {}

            # create asymmetrical key for the node,this is unique for each node
            self.pri_key = keys.UmbralPrivateKey.gen_key()
            self.pub_key = self.pri_key.get_pubkey()
            # create the key for digital signature
            self.signing_key = keys.UmbralPrivateKey.gen_key()
            self.verifying_key = self.signing_key.get_pubkey()
            self.signer = signing.Signer(self.signing_key)
            # save the keys as binary file
            key_pair["pri_key"] = self.pri_key.to_bytes()
            key_pair["pub_key"] = self.pub_key.to_bytes()
            key_pair["signing_key"] = self.signing_key.to_bytes()
            key_pair["verifying_key"] = self.verifying_key.to_bytes()
            with open("key_pair.pkl", "wb") as f:
                pickle.dump(key_pair, f)
                print("the key pair has been saved")

        else:
            with open("key_pair.pkl", "rb") as f:
                key_pair = pickle.load(f)
                pub_key = keys.UmbralPublicKey.from_bytes(key_pair["pub_key"])
                verifying_key = keys.UmbralPublicKey.from_bytes(
                    key_pair["verifying_key"])
                pri_key = keys.UmbralPrivateKey.from_bytes(key_pair["pri_key"])
                signing_key = keys.UmbralPrivateKey.from_bytes(
                    key_pair["signing_key"])
                self.pri_key = pri_key
                self.pub_key = pub_key
                self.signing_key = signing_key
                self.verifying_key = verifying_key
                self.signer = signing.Signer(self.signing_key)
                print("the key pair loads success")
def run_test():
    alices_private_key_bytes = keys.UmbralPrivateKey.gen_key().to_bytes()
    alices_private_key = keys.UmbralPrivateKey.from_bytes(
        alices_private_key_bytes)
    alices_public_key = alices_private_key.get_pubkey()

    # print("Alices private key:", alices_private_key.to_bytes())
    # print("Alices public key:", alices_public_key.to_bytes())

    alices_signing_key = keys.UmbralPrivateKey.gen_key()
    alices_verifying_key = alices_signing_key.get_pubkey()
    alices_signer = signing.Signer(private_key=alices_signing_key)

    bobs_private_key = keys.UmbralPrivateKey.gen_key()
    bobs_public_key = bobs_private_key.get_pubkey()

    plaintext = b'Proxy Re-encryption is cool!'
    ciphertext, capsule = pre.encrypt(alices_public_key, plaintext)

    cleartext = pre.decrypt(ciphertext=ciphertext,
                            capsule=capsule,
                            decrypting_key=alices_private_key)

    # Requires:
    kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key,
                                 signer=alices_signer,
                                 receiving_pubkey=bobs_public_key,
                                 threshold=10,
                                 N=20)

    capsule.set_correctness_keys(delegating=alices_public_key,
                                 receiving=bobs_public_key,
                                 verifying=alices_verifying_key)

    cfrags = list()
    for kfrag in kfrags[:10]:
        cfrag = pre.reencrypt(kfrag=kfrag, capsule=capsule)
        cfrags.append(cfrag)

    for cfrag in cfrags:
        capsule.attach_cfrag(cfrag)

    bob_cleartext = pre.decrypt(ciphertext=ciphertext,
                                capsule=capsule,
                                decrypting_key=bobs_private_key)

    print("Plain text: ", plaintext)
    print("bob_cleartext: ", bob_cleartext)

    assert bob_cleartext == plaintext
示例#19
0
def new_user(user_id):
    alices_private_key = keys.UmbralPrivateKey.gen_key()
    alices_public_key = alices_private_key.get_pubkey()

    alices_signing_key = keys.UmbralPrivateKey.gen_key()
    alices_verifying_key = alices_signing_key.get_pubkey()
    alices_signer = signing.Signer(private_key=alices_signing_key)
    users[user_id] = {
        'prk': alices_private_key,
        'pubk': alices_public_key,
        'signk': alices_signing_key,
        'signer': alices_signer
    }
    print(users)
    return "New User created"
示例#20
0
def digital_sign(iid, filename=None, text_data=None):
    print("Signing the File")
    with open(f"{ASSYMETRIC_KEY_PATH}/{iid}_private_key.pem",
              "rb") as key_file:
        print(f"Reading private_key of {iid}")
        private_key = key_file.read()
        private_key = keys.UmbralPrivateKey.from_bytes(private_key)
        print(private_key)
    if (filename):
        with open(f"{ENCRYPTED_FILES_PATH}/{filename}", 'rb') as f:
            data = f.read()
    if (text_data):
        data = text_data.encode()
    signature = signing.Signer(private_key)
    return base64.b64encode(signature(data)).decode()
def setup():
    show_debug("Setting up the environment...")
    # Generate encryption keys for Alice
    sk_a = keys.UmbralPrivateKey.gen_key(params)
    pk_a = sk_a.get_pubkey()

    # Generate singing keys for Alice
    sign_a = keys.UmbralPrivateKey.gen_key(params)
    verify_a = sign_a.get_pubkey()
    signer_a = signing.Signer(private_key=sign_a)

    # Generate encryption keys for Bob
    sk_b = keys.UmbralPrivateKey.gen_key(params)
    pk_b = sk_b.get_pubkey()

    return (pk_a, sk_a, signer_a, verify_a, pk_b, sk_b)
示例#22
0
文件: launcher.py 项目: VanyLaw/PoC
    def get(self):
        sk_filename = "pk1"
        sk = keys.UmbralPrivateKey.from_bytes(
            bytes.fromhex(open("data/pk/" + sk_filename).read()))
        vk = sk.get_pubkey()
        user_id = vk.to_bytes().hex()

        content = open("data/pk/" + sk_filename, "rb").read()
        ciphertext, capsule = pre.encrypt(vk, content)
        print(len(ciphertext), capsule.to_bytes())
        sha1 = hashlib.sha1(ciphertext).hexdigest()
        sha1_binary = bin(int(sha1, 16))[2:].zfill(32 * 4)
        print(sha1_binary, len(sha1_binary), sha1, 16)

        timestamp = time.time()
        sk_sign = signing.Signer(sk)
        signature = sk_sign((str(sha1) + str(timestamp)).encode("utf8"))
        assert signature.verify((str(sha1) + str(timestamp)).encode("utf8"),
                                vk)

        known_addresses_list = list(ControlHandler.known_addresses)
        addr = random.choice(known_addresses_list)
        http_client = tornado.httpclient.AsyncHTTPClient()
        # print(len(vk.to_bytes().hex()), vk.to_bytes().hex())
        # # print(len(bin(int(vk.to_bytes().hex(), 16))), bin(int(vk.to_bytes().hex(), 16)))
        # print(len(bytes(signature).hex()), bytes(signature).hex())
        while True:
            url = "http://%s:%s/get_group?groupid=%s" % (tuple(addr) +
                                                         (sha1_binary, ))
            try:
                response = yield http_client.fetch(
                    url
                )  #, method="POST", body=tornado.escape.json_encode(data)
            except Exception as e:
                print("Error: %s" % e)
            print(addr, response.body)
            res = tornado.escape.json_decode(response.body)
            if res["groupid"] == res["current_groupid"]:
                break
            addr = res["address"][0]

        url = "http://%s:%s/object?hash=%s&user_id=%s&timestamp=%s&signature=%s" % (
            tuple(addr) +
            (sha1, user_id, str(timestamp), bytes(signature).hex()))
        print(url)
        response = yield http_client.fetch(url, method="POST", body=ciphertext)
        print(len(ciphertext), ciphertext)
def get_reencryption_key(alice_priv_key_hex, alice_priv_signing_key_hex,
                         bob_pub_key_hex):
    alice_priv_key = keys.UmbralPrivateKey.from_bytes(
        bytes.fromhex(alice_priv_key_hex))
    alice_priv_signing_key = keys.UmbralPrivateKey.from_bytes(
        bytes.fromhex(alice_priv_signing_key_hex))
    bob_pub_key = keys.UmbralPublicKey.from_bytes(
        bytes.fromhex(bob_pub_key_hex))

    alices_signer = signing.Signer(private_key=alice_priv_signing_key)
    kfrags = pre.generate_kfrags(delegating_privkey=alice_priv_key,
                                 signer=alices_signer,
                                 receiving_pubkey=bob_pub_key,
                                 threshold=1,
                                 N=1)
    kfrag = kfrags[0]
    return kfrag.to_bytes().hex()
示例#24
0
 def generateKfrags(account: str, access_pub_key):
     with open(account + '_privacy', 'rb') as f:
         user_info_bytes = pickle.load(f)
         f.close()
     owner_pri_key = keys.UmbralPrivateKey.from_bytes(user_info_bytes['private_key'])
     owner_signing_key = keys.UmbralPrivateKey.from_bytes(user_info_bytes['signing_key'])
     signer = signing.Signer(private_key=owner_signing_key)
     kfrags = pre.generate_kfrags(delegating_privkey=owner_pri_key,
                                  signer=signer,
                                  receiving_pubkey=access_pub_key,
                                  threshold=1,
                                  N=2)
     res = {}
     bytes_kfrags = list()
     for v in kfrags:
         bytes_kfrags.append(v.to_bytes().decode('iso-8859-15'))
     res['kfrags'] = bytes_kfrags
     return res.__str__()
示例#25
0
def create_keyfrag():
    if (not request.json or not 't' in request.json
            or not 'delegating_secret' in request.json
            or not 'receiving' in request.json
            or not 'signer_secret' in request.json):
        abort(400)
    threshold = request.json['t']

    show_debug(request.json['delegating_secret'])

    sk_a = UmbralPrivateKey.from_bytes(binascii.unhexlify(
        request.json['delegating_secret'].encode()),
                                       params=params)
    pk_b = UmbralPublicKey.from_bytes(
        binascii.unhexlify(request.json['receiving'].encode()), params)
    sign_a = UmbralPrivateKey.from_bytes(binascii.unhexlify(
        request.json['signer_secret'].encode()),
                                         params=params)
    signer_a = signing.Signer(private_key=sign_a)

    show_debug("Generating kfrags")
    now = time.time() * 1000
    kfrags = pre.generate_kfrags(delegating_privkey=sk_a,
                                 signer=signer_a,
                                 receiving_pubkey=pk_b,
                                 threshold=threshold,
                                 N=nodes_num)
    end = time.time() * 1000
    gen_tot = end - now
    show_debug("Generated key fragment in: " + str(gen_tot))

    show_debug("Distributing kfrags")
    k_id = request.json['id']
    payload = {
        'capsule': request.json['capsule'],
        'delegating': request.json['pk'],
        'receiving': request.json['receiving'],
        'verifying': binascii.hexlify(sign_a.get_pubkey().to_bytes()).decode()
    }
    ree_tot = distribute_key_fragments(k_id, kfrags, payload, threshold)
    show_debug("Distributed key fragments")

    return jsonify({'gen_time': gen_tot, 'ree_time': ree_tot}), 201
示例#26
0
def createPolicy():
    json_data = json.loads(request.data.decode('utf-8'))
    alices_private_key = json_data['alices_private_key']
    alices_signing_key = json_data['alices_signing_key']
    bobs_public_key = json_data['bobs_public_key']
    alices_private_key = keys.UmbralPrivateKey.from_bytes(
        string_to_bytes(alices_private_key))
    bobs_public_key = keys.UmbralPublicKey.from_bytes(
        string_to_bytes(bobs_public_key))
    alices_signing_key = keys.UmbralPrivateKey.from_bytes(
        string_to_bytes(alices_signing_key))
    alices_signer = signing.Signer(private_key=alices_signing_key)
    kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key,
                                 signer=alices_signer,
                                 receiving_pubkey=bobs_public_key,
                                 threshold=3,
                                 N=5)
    kfrags_array.append(kfrags)
    print(kfrags_array)
    return jsonify(len(kfrags_array) - 1)
示例#27
0
 def getData(owner, reader, ciphertext, capsule_bytes) -> str:
     with open(owner + '_privacy', 'rb') as f:
         owner_info_bytes = pickle.load(f)
         f.close()
     owner_pri_key = keys.UmbralPrivateKey.from_bytes(owner_info_bytes['private_key'])
     owner_pub_key = owner_pri_key.get_pubkey()
     owner_signing_key = keys.UmbralPrivateKey.from_bytes(owner_info_bytes['signing_key'])
     owner_ver_key = owner_signing_key.get_pubkey()
     with open(reader + '_privacy', 'rb') as f:
         reader_info_bytes = pickle.load(f)
         f.close()
     reader_pri_key = keys.UmbralPrivateKey.from_bytes(reader_info_bytes['private_key'])
     reader_pub_key = reader_pri_key.get_pubkey()
     reader_ver_key = keys.UmbralPrivateKey.from_bytes(reader_info_bytes['signing_key']).get_pubkey()
     signer = signing.Signer(private_key=owner_signing_key)
     kfrags = pre.generate_kfrags(delegating_privkey=owner_pri_key,
                                  signer=signer,
                                  receiving_pubkey=reader_pub_key,
                                  threshold=1,
                                  N=2)
     capsule = pre.Capsule.from_bytes(capsule_bytes, owner_pub_key.params)
     capsule.set_correctness_keys(delegating=owner_pub_key,
                                  receiving=reader_pub_key,
                                  verifying=owner_ver_key)
     cfrags = list()
     for kfrag in kfrags:
         cfrag = pre.reencrypt(kfrag=kfrag, capsule=capsule)
         cfrags.append(cfrag)
     for cfrag in cfrags:
         capsule.attach_cfrag(cfrag)
     img_bytes = pre.decrypt(ciphertext=ciphertext,
                             capsule=capsule,
                             decrypting_key=reader_pri_key)
     img = base64.b64decode(img_bytes)
     with open('return_example.jpeg', 'wb') as f:
         f.write(img)
         f.close()
     path = os.path.abspath(__file__) + '/return_example.jpeg'
     return path
示例#28
0
def digital_sign(): #uid, text_data=None, filename=None
    uid = request.args.get('uid')
    print(uid)
    filename = request.args.get('filepath')
    text_data = request.args.get("text_data")
    print("Signing the File")
    try:
        with open(f"{ASSYMETRIC_KEY_PATH}/{uid}_private_key.pem", "rb") as key_file:
            print(f"Reading private_key of {uid}")
            private_key = key_file.read()
            private_key = keys.UmbralPrivateKey.from_bytes(private_key)
            print(private_key)
    except:
        return jsonify({'status': False})
    if(filename):
        with open(f"{ENCRYPTED_FILES_PATH}/{filename}", 'rb') as f:
            data = f.read()
    if(text_data):
        data = text_data.encode()
    signature = signing.Signer(private_key)
    print("the sign is ->",base64.b64encode(signature(data)).decode())
    return base64.b64encode(signature(data)).decode()
示例#29
0
文件: views.py 项目: sriharikapu/ews
    def post(self, request, *args, **kwargs):
        data = QueryDict(request.body)
        # import pdb;pdb.set_trace()
        global alices_private_key, alices_public_key, plaintext
        plaintext = request.FILES.get('file', [])
        plaintext = plaintext.read()
        alices_private_key = keys.UmbralPrivateKey.gen_key()
        alices_public_key = alices_private_key.get_pubkey()

        alices_signing_key = keys.UmbralPrivateKey.gen_key()
        alices_verifying_key = alices_signing_key.get_pubkey()
        alices_signer = signing.Signer(private_key=alices_signing_key)
        global capsule, ciphertext
        ciphertext, capsule = pre.encrypt(alices_public_key, plaintext)
        # print(alices_private_key.to_bytes())
        # print(alices_public_key.to_bytes())
        print('CAPSULE:' + str(capsule.to_bytes()))
        print('CIPHERTEXT: ' + str(ciphertext))
        tem = {}
        self.initialize_map(alices_private_key.to_bytes(), ciphertext, capsule)
        tem['ciphertext'] = CIPHER
        tem['capsule'] = CAPSULE
        return HttpResponse(json.dumps(tem), status=201)
示例#30
0
文件: dashboard.py 项目: VanyLaw/PoC
    def get(self):
        sk_filename = "pk1"
        sk = keys.UmbralPrivateKey.from_bytes(
            bytes.fromhex(open("data/pk/" + sk_filename).read()))
        vk = sk.get_pubkey()
        user_id = vk.to_bytes().hex()
        http_client = tornado.httpclient.AsyncHTTPClient()

        # get root tree hash from blockchain, from random node
        timestamp = time.time()
        sk_sign = signing.Signer(sk)
        signature = sk_sign(str(timestamp).encode("utf8"))
        assert signature.verify(str(timestamp).encode("utf8"), vk)

        known_addresses_list = list(ControlHandler.known_addresses)
        addr = random.choice(known_addresses_list)
        # print(len(vk.to_bytes().hex()), vk.to_bytes().hex())
        # print(len(bytes(signature).hex()), bytes(signature).hex())
        url = "http://%s:%s/user?user_id=%s&timestamp=%s&signature=%s" % (
            tuple(addr) + (user_id, str(timestamp), bytes(signature).hex()))
        try:
            response = yield http_client.fetch(
                url)  #, method="POST", body=tornado.escape.json_encode(data)
            user = tornado.escape.json_decode(response.body)
            # print(user)
            groupid = user["groupid"]
            folder_hash = user["folder_hash"]
        except Exception as e:
            print("Error: %s" % e)

        # get content object and capsule from the group
        timestamp = time.time()
        sk_sign = signing.Signer(sk)
        signature = sk_sign((str(folder_hash) + str(timestamp)).encode("utf8"))
        assert signature.verify(
            (str(folder_hash) + str(timestamp)).encode("utf8"), vk)

        addr, _ = yield get_group(groupid)
        print(_, groupid)
        url = "http://%s:%s/object?hash=%s&user_id=%s&timestamp=%s&signature=%s" % (
            tuple(addr) +
            (folder_hash, user_id, str(timestamp), bytes(signature).hex()))
        response = yield http_client.fetch(url)
        ciphertext = response.body

        url = "http://%s:%s/capsule?hash=%s&user_id=%s&timestamp=%s&signature=%s" % (
            tuple(addr) +
            (folder_hash, user_id, str(timestamp), bytes(signature).hex()))
        response = yield http_client.fetch(url)
        capsule = response.body

        # decode
        print(ciphertext, capsule)
        cleartext = pre.decrypt(ciphertext=ciphertext,
                                capsule=pre.Capsule.from_bytes(
                                    capsule, umbral.config.default_params()),
                                decrypting_key=sk)

        # put file
        content = open("data/pk/" + sk_filename, "rb").read()
        ciphertext, capsule = pre.encrypt(vk, content)
        print(len(ciphertext), capsule.to_bytes())
        sha1 = hashlib.sha1(ciphertext).hexdigest()
        sha1_binary = bin(int(sha1, 16))[2:].zfill(32 * 4)
        print(sha1_binary, len(sha1_binary), sha1, 16)
        addr, groupid = yield get_group(sha1_binary)

        timestamp = time.time()
        sk_sign = signing.Signer(sk)
        signature = sk_sign((str(sha1) + str(timestamp)).encode("utf8"))
        assert signature.verify((str(sha1) + str(timestamp)).encode("utf8"),
                                vk)

        url = "http://%s:%s/object?hash=%s&user_id=%s&timestamp=%s&signature=%s" % (
            tuple(addr) +
            (sha1, user_id, str(timestamp), bytes(signature).hex()))
        http_client = tornado.httpclient.AsyncHTTPClient()
        response = yield http_client.fetch(url, method="POST", body=ciphertext)
        print(len(ciphertext), ciphertext)

        # update
        data = tornado.escape.json_decode(cleartext)
        data["filename"] = [sha1, len(ciphertext), groupid, time.time()]

        # encode
        content = tornado.escape.json_encode(data).encode("utf8")
        ciphertext, capsule = pre.encrypt(vk, content)
        folder_size = str(len(ciphertext))
        block_size = len(ciphertext)
        folder_hash = hashlib.sha1(ciphertext).hexdigest()
        folder_hash_binary = bin(int(folder_hash, 16))[2:].zfill(32 * 4)
        addr, groupid = yield get_group(folder_hash_binary)
        print("ciphertext", len(ciphertext), "capsule",
              capsule.to_bytes().hex())

        # put
        timestamp = time.time()
        sk_sign = signing.Signer(sk)
        signature = sk_sign(str(timestamp).encode("utf8"))
        assert signature.verify(str(timestamp).encode("utf8"), vk)

        url = "http://%s:%s/user?user_id=%s&folder_hash=%s&block_size=%s&folder_size=%s&groupid=%s&capsule=%s&timestamp=%s&signature=%s" \
                % (tuple(addr)+(user_id, folder_hash, block_size, folder_size, groupid, capsule.to_bytes().hex(), timestamp, bytes(signature).hex()))
        try:
            response = yield http_client.fetch(url,
                                               method="POST",
                                               body=ciphertext)
        except Exception as e:
            print("Error: %s" % e)