Example #1
0
    def test_decrypt(self):
        # generate an ECIES key pair
        skey = ecies.gen_private_key()
        pkey = ecies.gen_public_key(skey)
        tag = random_scalar()

        # test decryption
        self.assertEqual(
            ecies.decrypt(skey, tag, ecies.encrypt(pkey, tag, '')), '')
        self.assertEqual(
            ecies.decrypt(skey, tag, ecies.encrypt(pkey, tag, 'message')),
            'message')
        self.assertEqual(
            ecies.decrypt(
                skey, tag,
                ecies.encrypt(pkey, tag,
                              'Four score and seven long messages ago')),
            'Four score and seven long messages ago')
        self.assertEqual(
            ecies.decrypt(skey, tag, ecies.encrypt(pkey, tag, str(G))), str(G))

        # test bad types
        with self.assertRaises(TypeError):
            ecies.decrypt(None, tag, ecies.encrypt(None, tag, ''))
        with self.assertRaises(TypeError):
            ecies.decrypt(skey, tag, None)
Example #2
0
 def icies_test(self, sk_hex, pk_hex, data):
     # assymtetric encryption/decryption test
     print(decrypt(sk_hex, encrypt(pk_hex, data)))
     secp_k = generate_key()
     sk_bytes = secp_k.secret  # bytes
     pk_bytes = secp_k.public_key.format(True)  # bytes
     print(decrypt(sk_bytes, encrypt(pk_bytes, data)))
Example #3
0
def gen_account(public_key,a):
    r = dumb25519.random_scalar()
    co = G*a + H*r

    ek = dumb25519.random_scalar()
    s = dumb25519.hash_to_scalar(str(public_key.tpk)+str(public_key.spk)+str(public_key.X)+str(ek))
    pk = public_key.X + H*s

    _ek = ecies.encrypt(public_key.tpk,str(pk)+str(co),str(ek))
    _a = ecies.encrypt(public_key.spk,str(pk)+str(co),str(a))
    _r = ecies.encrypt(public_key.spk,str(pk)+str(co),str(r))

    return Account(pk,co,_ek,_a,_r),DepositKey(a,r)
Example #4
0
def ecciespy_encrypt(text):
    eth_k = generate_eth_key()
    prvhex = eth_k.to_hex()
    pubhex = eth_k.public_key.to_hex()
    data = bytes(text,'utf-8')
    decrypt(prvhex, encrypt(pubhex, data))
    return True 
def ies(ptxt):
    sk = generate_key()
    sk_bytes = sk.secret
    pk_bytes = sk.public_key.format(True)
    ctxt = encrypt(pk_bytes, ptxt.encode())
    print("Ctxt:", ctxt)
    return decrypt(sk_bytes, ctxt)
Example #6
0
    def test_elliptic(self):
        data = self.test_string
        k = generate_eth_key()
        prvhex = k.to_hex()
        pubhex = k.public_key.to_hex()
        self.assertEqual(data, decrypt(prvhex, encrypt(pubhex, data)))

        k = generate_key()
        prvhex = k.to_hex()
        pubhex = k.public_key.format(False).hex()
        self.assertEqual(data, decrypt(prvhex, encrypt(pubhex, data)))

        k = generate_key()
        prvhex = k.to_hex()
        pubhex = k.public_key.format(True).hex()
        self.assertEqual(data, decrypt(prvhex, encrypt(pubhex, data)))
Example #7
0
async def handle_request(reader, writer):
    data = await reader.read(1024)
    addr = writer.get_extra_info('peername')
    print(f"Received task from {addr!r}")
    msg = json.loads(data.decode())
    print(msg)
    send_msg = {'status': 'no'}
    productId = msg['productId']
    public = msg['public']
    sql = "SELECT * FROM apps_key_db_one WHERE productId = %s" % (
        int(productId))
    cursor.execute(sql)
    data = cursor.fetchone()
    encrypt_key = b2a_hex(
        encrypt(
            public,
            decrypt(keyring.get_password("DRMDEMO", "keyManagerOnePrivate"),
                    a2b_hex(data[2])))).decode()

    # print(encrypt_key)

    send_msg['status'] = 'ok'
    send_msg['key'] = encrypt_key
    send_data = json.dumps(send_msg)

    writer.write(send_data.encode())
    await writer.drain()

    print(f"finsh {addr!r} work")
    writer.close()
Example #8
0
def keygen():
    dk_string1 = getpass.getpass(prompt="Decryption Key 1: ")
    if len(dk_string1) < 6:
        raise ValueError(
            "For your own security each passphrase should be at least 6 characters"
        )
    sk_int1 = int(hashlib.sha256(dk_string1.encode()).hexdigest(), 16)

    dk_string2 = getpass.getpass(prompt="Decryption Key 2: ")
    if len(dk_string2) < 6:
        raise ValueError(
            "For your own security each passphrase should be at least 6 characters"
        )
    sk_int2 = int(hashlib.sha256(dk_string2.encode()).hexdigest(), 16)

    sk_int = (sk_int1 * sk_int2) % curves.SECP256k1.order

    sk = keys.SigningKey.from_secret_exponent(sk_int,
                                              curve=curves.SECP256k1,
                                              hashfunc=hashlib.sha256)
    pk = sk.verifying_key.pubkey

    pub = "04" + hex(pk.point.x())[2:] + hex(pk.point.y())[2:]
    try:
        c = encrypt(pub, b'abc')
    except:
        raise ValueError(
            "Sorry: this passphrase combination does not work. Try again and change one passphrase!"
        )

    print("Encryption Key:", pub)
Example #9
0
 def encrypt_key(self, pub_key, key_str):
     try:
         pub_point = pub_key.point()
         pub = coincurve.PublicKey.from_point(x=pub_point.x(),
                                              y=pub_point.y())
         return base64.urlsafe_b64encode(encrypt(pub.format(), key_str))
     except:
         return ''
Example #10
0
def AsymEncrypt(public_key_str, plaintext):
    try:
        public_point = PublicKey(public_key_str).point()
        public_key = coincurve.PublicKey.from_point(x=public_point.x(),
                                                    y=public_point.y())
        return encrypt(public_key.format(True), plaintext)
    except:
        return b""
Example #11
0
def test_encryption_decryption():
    eth_k = generate_eth_key()
    private_key_hex = eth_k.to_hex()  # hex string
    public_key_hex = eth_k.public_key.to_hex()  # hex string
    data = 'hi there'
    result = decrypt(private_key_hex, encrypt(public_key_hex, data.encode()))
    print(result)
    print('decoded=' + result.decode())
    assert result == data.encode()
    assert data == result.decode()
Example #12
0
    def attmpt4_alg(pub_key, data):
        i_pk = int(pub_key, 16)
        num_bytes = i_pk.bit_length() // 8 + 1
        # Only works with big endian despite sys.byteorder returning 'little'
        # Maybe something to do with how bitcoin does it.
        endianness = 'big'
        b_pk = i_pk.to_bytes(num_bytes, endianness)
        encrypted = ecies.encrypt(b_pk, data)

        return encrypted
Example #13
0
    def atmpt2():
        ''' solution that works...'''
        from bit import Key
        wif_private_key = 'cPhnVqon8qro8WmFJ5ma24Lrp59XnudnhywdkPcERw4xM9Mhbr1e'
        private_key = Key(wif_private_key)
        encrypted = ecies.encrypt(private_key.public_key, b'this is a test')
        decrypted = ecies.decrypt(private_key._pk.secret, encrypted)

        print('encrypted', encrypted)
        print('decrypted', decrypted)
Example #14
0
def encrypt_user_data(json_data, priv_key=None, pub_key=None):
    if priv_key is None and pub_key is None:
        raise Exception(
            "Only one of {priv_key, pub_key} may retain a value of None")

    data = encode_and_format(json_data)

    if pub_key is not None:
        i_pk = int(pub_key, 16)
        num_bytes = i_pk.bit_length() // 8 + 1
        # Only works with big endian despite sys.byteorder returning 'little'
        # Maybe something to do with how bitcoin does it.
        endianness = 'big'
        b_pk = i_pk.to_bytes(num_bytes, endianness)
        encrypted = ecies.encrypt(b_pk, data)
    else:
        key = Key(priv_key)
        encrypted = ecies.encrypt(key.public_key, data)
    return encrypted
Example #15
0
 def cipher_message(self, message):
     _logger.info("Usuario %s: Está cifrando un mensaje." % self._name)
     friend = message.split(":")[0]
     if friend in self._keys_holder:
         _logger.info("Usuario %s: Llave pública de %s en el llavero personal." % (self._name, friend))
         cypher_messagge = encrypt(self._keys_holder.get(friend), message.split(":")[1].encode())
         _logger.info("Usuario %s: Mensaje cifrado: %s" % (self._name, cypher_messagge))
         return cypher_messagge
     else:
         _logger.error("Usuario %s: Llave pública de %s no está en el llavero personal." % (self._name, friend))
         return False
Example #16
0
 def _calc_invitation(pk, addr, note):
     if len(note) > MAX_NOTE_LEN:
         raise Exception("note too long")
     note_bytes = bytes(note, 'utf-8')
     extended_note_bytes = note_bytes
     if len(note_bytes) != MAX_NOTE_LEN:
         extended_note_bytes += urandom(MAX_NOTE_LEN - len(note_bytes))
     raw_invitation = ZkTransfer._pad_hexstr(addr) + Web3.toBytes(
         len(note_bytes)) + extended_note_bytes
     invitation = encrypt(pk, raw_invitation)
     return invitation
Example #17
0
def run_test(client, base_ddo_url, events_instance, flags=None, encryption_key=None):
    web3 = get_web3()
    block = web3.eth.blockNumber
    _ddo = new_ddo(test_account1, web3, f'dt.{block}')
    did = _ddo.id
    ddo_string = json.dumps(dict(_ddo))
    data = Web3.toBytes(text=ddo_string)
    _flags = flags or 0
    if flags is not None:
        data = lzma.compress(data)
        # mark bit 1
        _flags = _flags | 1

    if encryption_key is not None:
        # ecies encrypt - bit 2
        _flags = _flags | 2
        key = eth_keys.KeyAPI.PrivateKey(encryption_key)
        data = ecies.encrypt(key.public_key.to_hex(), data)

    send_create_update_tx('create', did, bytes([_flags]), data, test_account1)
    get_event(EVENT_METADATA_CREATED, block, did)
    events_instance.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo['id'] == did

    _ddo['service'][0]['attributes']['main']['name'] = 'Updated ddo by event'
    ddo_string = json.dumps(dict(_ddo))
    data = Web3.toBytes(text=ddo_string)
    if flags is not None:
        data = lzma.compress(data)

    if encryption_key is not None:
        key = eth_keys.KeyAPI.PrivateKey(encryption_key)
        data = ecies.encrypt(key.public_key.to_hex(), data)

    send_create_update_tx('update', did, bytes([_flags]), data, test_account1)
    get_event(EVENT_METADATA_UPDATED, block, did)
    events_instance.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo['id'] == did
    assert published_ddo['service'][0]['attributes']['main']['name'] == 'Updated ddo by event'
Example #18
0
def index():
    prv = request.form.get("prv", "")
    pub = request.form.get("pub", "")
    data = request.form.get("data", "")
    if prv and data:
        decrypted = decrypt(prv, bytes.fromhex(data))
        return decrypted
    elif pub and data:
        encrypted = encrypt(pub, data.encode())
        return encrypted.hex()
    else:
        abort(400)
Example #19
0
def pub_encrypt(text, public_key):
    """
    text: bytes
    returns bytes type object
    """
    try:
        if isinstance(text, str):
            text = text.encode()
        return encrypt(public_key, text)
    except Exception as e:
        logging.error(f"While encrypting data with publickey{public_key} and data {text}is {e}")
        raise Exception("Couldnt encrypt with public key")
def encrypt_url():
    raw_text = str(url_display.get('1.0', tk.END))
    raw_text = bytes(raw_text, 'utf-8')
    privKey = generate_eth_key()
    privKeyHex = privKey.to_hex()
    pubKeyHex = privKey.public_key.to_hex()
    encrypted = encrypt(pubKeyHex, raw_text)
    encrypted = binascii.hexlify(encrypted)
    result = '\n\nEncrypted text:\n{}'.format(encrypted)
    tab5_display_text.insert(tk.END, result)
    result1 = '\n{} '.format(privKeyHex)
    tab5_display1.insert(tk.END, result1)
Example #21
0
    def test_elliptic(self):
        data = self.test_string
        k = generate_eth_key()
        sk_hex = k.to_hex()
        pk_hex = k.public_key.to_hex()
        self.assertEqual(data, decrypt(sk_hex, encrypt(pk_hex, data)))

        k = generate_key()
        sk_hex = k.to_hex()
        pk_hex = k.public_key.format(False).hex()
        self.assertEqual(data, decrypt(sk_hex, encrypt(pk_hex, data)))
        self.assertEqual(
            data,
            decrypt(bytes.fromhex(sk_hex), encrypt(bytes.fromhex(pk_hex),
                                                   data)))

        k = generate_key()
        sk_hex = k.to_hex()
        pk_hex = k.public_key.format(True).hex()
        self.assertEqual(data, decrypt(sk_hex, encrypt(pk_hex, data)))
        self.assertEqual(
            data,
            decrypt(bytes.fromhex(sk_hex), encrypt(bytes.fromhex(pk_hex),
                                                   data)))

        self.assertRaises(TypeError, encrypt, 1, data)
        self.assertRaises(TypeError, decrypt, 1,
                          encrypt(bytes.fromhex(pk_hex), data))
def encrypt_text():
    raw_text = str(entry.get('1.0', tk.END))  #Get input
    raw_text = bytes(raw_text, 'utf-8')
    privKey = generate_eth_key()  #Generate Private Key
    privKeyHex = privKey.to_hex()  #Convert it to Hexadecimal
    pubKeyHex = privKey.public_key.to_hex()  #Make Public Key
    encrypted = encrypt(pubKeyHex, raw_text)
    encrypted = binascii.hexlify(encrypted)
    result = '\n\nEncrypted text:\n{}'.format(encrypted)  #Print Result
    tab3_display.insert(tk.END, result)
    result1 = '\n{}'.format(privKeyHex)
    #result1 = '\nPrivate Key: {}\nPublic Key: {}'.format(privKeyHex,pubKeyHex)
    tab3_display1.insert(tk.END, result1)
def test_encrypt_and_descrypt_signature():
    # Rsk Address 0x67a03d727b61a4ffd3721f79d52a3baea1b63ea0
    pubkey = 'e00f009e7d4308ac39216bbe964d7ac933ac4dfce8b0c369848f4fcae4664fca2dab' \
             '9a0e3e9db5eef5fb3de25f78dd0161f707a0075a179b1419d72121aa0c80'
    privkey = '3f5d3cda6320fd57f4d47e50c3404e7e43cfb60968d7ef13eb6873760b445e47'
    # This is a result after sign the following data transport02.raiden.network, with this privkey and encode_hex
    signed_data = b'0x30f852f75ea11df467e8a518e3e7ceec9e106f4c2c50027e3277e239af06a' \
                  b'f0730fef7b16f32943b62b03fe0e479a555d5bf7686318327b9c15f514a99da07f11c'

    encrypt_data = encrypt(pubkey, signed_data)
    descrypt_data = decrypt(privkey, encrypt_data)

    assert signed_data == descrypt_data
Example #24
0
    def encrypt(cls, plain: AnyStr, pub_key) -> bytes:
        """
        Encrypt with receiver's public key

        :param plain: data to encrypt
        :param pub_key: public key
        :return: encrypted data
        """
        if type(plain) == str:
            plain = plain.encode("utf8")
        if type(plain) != bytes:
            raise TypeError("message only support str or bytes.")
        cipher = ecies.encrypt(pub_key, plain)
        return cipher
Example #25
0
    def encrypt(self, message, public_key=None):
        """
        Return message encrypted with public key

        @param message bytes
        @param public_key bytes
        """
        if isinstance(message, str):
            message = message.encode()

        if public_key is None:
            public_key = self.public_key
        else:
            public_key = KeyAPI.PublicKey(public_key)
        return ecies.encrypt(message, public_key)
Example #26
0
    def attmpt_paicoin():
        pub_key_addr = 'MnqtQVYSkEinTukeaz2zQdJbo4fivzJMip'
        pub_key = '02b01692bb20206f03417f9cfd3dfc51e545feb1d7ff5f5f6648a9747988009e8a'
        pub_key = '031a5808d3d801fb08e43209566803e950e2bad98b1bec39ac0f736799b1b1533a'
        priv_key = 'aZiUxsYszMG6REqQ8kLiaTU9TNLoyMwPuX7q24YmbF5AA7kDw784'

        i_pk = int(pub_key, 16)
        num_bytes = i_pk.bit_length() // 8 + 1
        # Only works with big endian despite sys.byteorder returning 'little'
        # Maybe something to do with how bitcoin does it.
        endianness = 'big'
        b_pk = i_pk.to_bytes(num_bytes, endianness)
        encrypted = ecies.encrypt(
            b_pk, b'We have had success with the an even public key')
        decrypted = ecies.decrypt(sk._pk.secret, encrypted)
Example #27
0
def encrypt_w_pubkey(data, public_key):
    ##this encrypts the mnemonic witht he public key
    ##Mnemonic must be in bytes
    if isinstance(data, str):
        data = data.encode()

    try:
        encrypted_data = encrypt(public_key, data)
    except Exception as e:
        logger.error(
            f"While encrypting data with publickey{public_key} and data {data} is {e}"
        )
        raise Exception("Couldnt encrypt with public key")
    ##hex encoding aes key
    return encrypted_data
Example #28
0
def generate(request):
    private_key = utils.sha3(os.urandom(4096))
    raw_address = utils.privtoaddr(private_key)
    addressif = address.to_normalized_address(raw_address)
    keyether = utils.encode_hex(private_key)
    sk = SigningKey.from_string(bytes.fromhex(keyether), curve=SECP256k1)
    public_key = sk.get_verifying_key()  #public_key
    pkey = public_key.to_string().hex().strip()
    data = b'https://darchnetwork.com/'
    encryptedval = encrypt(pkey, data)
    print("encryptedval", utils.encode_hex(encryptedval))
    decryptedvalue = decrypt(keyether, encryptedval)
    print("decrypted value is here", decryptedvalue)
    #public_key = public_key.to_string().hex()
    return render(request, "homomorphic/skeleton.html", locals())
Example #29
0
def sendMediaLink(userId, destId, mediaId, address):
    sort_contract = init_contract(address)
    isCreator = sort_contract.functions.isCreator(userId).call()
    if not isCreator:
        return "Function Not available for you\n"

    mediaBuyer = sort_contract.functions.getMediaBuyer(mediaId).call()
    if destId not in mediaBuyer:
        return "Media not bought by the user\n"

    mediaAlreadyHave = sort_contract.functions.getMediaAlreadyHave(
        mediaId).call()
    if destId in mediaAlreadyHave:
        return "Media Link already sent to the user\n"

    sender_user = getUserByID(userId, address)
    receiver_user = getUserByID(destId, address)
    sender_address = sender_user[3]
    receiver_address = receiver_user[3]

    receiver_pubkey = receiver_user[4]

    mediaURL = str(random.randrange(1, 100000))
    mediaURL_encrypted = encrypt(receiver_pubkey, mediaURL.encode())
    mediaURL_encrypted = "".join(
        ["{:02X}".format(c) for c in mediaURL_encrypted])

    # w3.eth.sendTransaction({'to':w3.toChecksumAddress(receiver), 'from':w3.toChecksumAddress(sender), 'value':w3.toWei(0, "ether"), 'data':w3.toHex(mediaURL.encode())})

    tx_hash = sort_contract.functions.sendMediaLink(
        userId, destId, mediaId, str(mediaURL_encrypted)).transact({
            'txType':
            "0x1",
            'from':
            w3.eth.accounts[0],
            'gas':
            2409638
        })
    receipt1 = w3.eth.getTransactionReceipt(tx_hash)

    while ((receipt1 is None)):
        time.sleep(1)
        receipt1 = w3.eth.getTransactionReceipt(tx_hash)
    if receipt1 is not None:
        print("media:{0}".format(receipt1['gasUsed']))
        print("Link Sent")

    return "Done"
 def _encrypt_nonce(self, pub_key, nonce, key_type):
     '''
     method responsible for generating the encrypted nonce
     :param pub_key: the public key used to encrypt the nonce
     :param nonce: the nonce to be encrypted
     :param key_type: the type of key being used for the encryption
     :return: the nonce encrypted with the public key
     '''
     if key_type.upper() == global_variables.SECP256k1_TYPE:
         #key = ecies.utils.generate_eth_key()
         #priv_key = key.to_hex()
         #pub_key = key.public_key.to_hex()
         encrypted_nonce = ecies.encrypt(str(pub_key), bytes(nonce, 'utf-8'))
         return encrypted_nonce
     else:
         # not in supported key types
         raise ValueError('invalid key type specified')