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 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 receive(private_key, account): ek = dumb25519.Scalar( int( ecies.decrypt(private_key.tsk, str(account.pk) + str(account.co), account._ek))) a = dumb25519.Scalar( int( ecies.decrypt(private_key.ssk, str(account.pk) + str(account.co), account._a))) r = dumb25519.Scalar( int( ecies.decrypt(private_key.ssk, str(account.pk) + str(account.co), account._r))) public_key = stealth.gen_public_key(private_key) s = dumb25519.hash_to_scalar( str(public_key.tpk) + str(public_key.spk) + str(ek)) if G * a + H * r != account.co: raise Exception('Bad account commitment!') if public_key.X + H * s != account.pk: raise Exception('Bad account public key!') xs = private_key.x + s return WithdrawalKey(xs, a, r, T * xs.invert())
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)))
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)
def AsymDecrypt(private_key_str, ciphertext): try: private_key = coincurve.PrivateKey.from_hex( repr(PrivateKey(private_key_str))) return decrypt(private_key.secret, ciphertext) except: return b""
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)
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()
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)))
def get_machine_identifer(self, ips_queue): """Ping worker implementation. Parameters ---------- jobs_queue : Queue Returns ------- None """ machine_identifers = {} while True: ip = ips_queue.get() if ip is None: return machine_identifers url = 'http://{}:{}/encrypted_identifer'.format(ip, CLIENT_APP_PORT) try: response = requests.post(url, data=self.pubkey.encode(), headers={'Content-Type': 'application/octet-stream'}, timeout=5) except requests.exceptions.ConnectionError: continue if not response.ok: continue encrypted_machine_identifer = response.content machine_identifer = decrypt(self.prvkey, encrypted_machine_identifer) machine_identifers.update({ip: machine_identifer.decode()})
def decrypt(self, encrypted_message): """ Return decrypted message with private key @param encrypted_message bytes """ return ecies.decrypt(encrypted_message, self.private_key)
def unlock(): fname = sys.argv[1] dk_string1 = getpass.getpass(prompt="Decryption Key 1: ") sk_int1 = int(hashlib.sha256(dk_string1.encode()).hexdigest(), 16) dk_string2 = getpass.getpass(prompt="Decryption Key 2: ") sk_int2 = int(hashlib.sha256(dk_string2.encode()).hexdigest(), 16) sk = hex((sk_int1 * sk_int2) % curves.SECP256k1.order)[2:] fpath = os.path.join(os.path.join(os.path.expanduser("~"), "Desktop"), fname) with open(fpath, "rb") as f: data = f.read() c = base64.b64decode(data) try: data = decrypt(sk, c) except: raise ValueError( "Decryption failed. Are you sure the passphrases entered were correct?" ) zipname = os.path.join(os.path.join(os.path.expanduser("~"), "Desktop"), fname + ".zip") with open(zipname, "wb") as f: f.write(data) os.remove( os.path.join(os.path.join(os.path.expanduser("~"), "Desktop"), fname))
def decrypt(wif_private_key, torrent_path, cfg): path = get_torrent_data_path(torrent_path, cfg) priv_key = Key(wif_private_key) with open(path, 'rb') as f: encrypted_s = f.read() unencrypted_s = ecies.decrypt(priv_key._pk.secret, encrypted_s) unencrypted_j = json.loads(unencrypted_s) return unencrypted_j
def get_dec(path): with open(path, 'r') as f: data = f.read() try: return str(decrypt(prv_key, bytes.fromhex(data)), encoding="utf-8") except Exception as e: print(str(e)) return data
def do_decrypt(encrypted_document, provider_wallet): key = get_private_key(provider_wallet) try: return ecies.decrypt( key.to_hex(), Web3.toBytes(hexstr=encrypted_document)).decode(encoding="utf-8") except Exception: return None
def decrypt_url(): encrypted = str(url_display.get('1.0', tk.END)) encrypted = bytes(encrypted, 'utf-8').strip() encrypted = binascii.unhexlify(encrypted) privKeyHex = str(tab5_display1.get('1.0', tk.END)).strip() decrypted = decrypt(privKeyHex, encrypted) result = '\n\nDecrypted text:\n{}'.format(decrypted) tab5_display_text.insert(tk.END, result)
def decrypt_text(): encrypted = str(entry.get('1.0', tk.END)) #Get input encrypted = bytes( encrypted, 'utf-8').strip() #Convert to bytes and remove white spaces encrypted = binascii.unhexlify(encrypted) privKeyHex = str(tab3_display1.get('1.0', tk.END)).strip() decrypted = decrypt(privKeyHex, encrypted) result = '\n\nDecrypted text:\n{}'.format(decrypted) #Print Result tab3_display.insert(tk.END, result)
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()
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)
def decrypt(cls, cipher: bytes) -> bytes: """ Decrypt with private key :param cipher: :return: """ if type(cipher) != bytes: raise TypeError("cipher only support bytes.") return ecies.decrypt(cls.priv_key, cipher)
def login_or_register_light_client(client: GMatrixClient, **kwargs): if kwargs['encrypted_light_client_password_signature'] is not None: descrypt_light_client_password_signature = \ decrypt(kwargs['private_key_hub'], bytes.fromhex(kwargs['encrypted_light_client_password_signature'])) if kwargs['encrypted_light_client_display_name_signature'] is not None: descrypt_light_client_display_name_signature = \ decrypt(kwargs['private_key_hub'], bytes.fromhex(kwargs['encrypted_light_client_display_name_signature'])) if kwargs['encrypted_light_client_seed_for_retry_signature'] is not None: desctypt_seed_retry_signature = \ decrypt(kwargs['private_key_hub'], bytes.fromhex(kwargs['encrypted_light_client_seed_for_retry_signature'])) server_url = client.api.base_url server_name = urlparse(server_url).netloc base_username = to_normalized_address(kwargs['light_client_address']) user = _check_previous_login(client, kwargs['prev_user_id'], kwargs['prev_access_token'], base_username, server_name) if user is None: # password is signed server address password = descrypt_light_client_password_signature.decode("utf-8") seed = decode_hex(desctypt_seed_retry_signature.decode("utf-8"))[-32:] _try_login_or_register(client, base_username, password, server_name, server_url, seed) name = descrypt_light_client_display_name_signature.decode("utf-8") user = client.get_user(client.user_id) user.set_display_name(name) log.info("Login or register for LightCLient with address " + base_username + " is successfully run") return user
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)
def getMediaURL(userId, mediaId, address): sort_contract = init_contract(address) mediaURL_encrypted = sort_contract.functions.getMediaURL(userId, mediaId).call() if "Error" in mediaURL_encrypted: return mediaURL_encrypted mediaURL_encrypted = bytes.fromhex(mediaURL_encrypted) mediaURL_decrypted = decrypt(prv_key, mediaURL_encrypted) print("Media Url for Media ID %d = %s" % (mediaId, mediaURL_decrypted.decode())) return "Done"
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
def decrypt_w_privkey(encrypted_data, private_key): ##this encrypts the mnemonic witht he public key data = binascii.unhexlify(encrypted_data) ##hex encoding aes key try: decrypted_data = decrypt(private_key, data) except Exception as e: logger.error( f"While encrypting data with private key {private_key} and data {data} is {e}" ) raise Exception("Couldnt decrypt with private key") return decrypted_data
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)
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())
def attmpt4_even_pub_key(): from bit import Key pub_key = '02b01692bb20206f03417f9cfd3dfc51e545feb1d7ff5f5f6648a9747988009e8a' priv_key = 'cSetqogg21eiTnhuZ79ru4LBSPiGyfZPDiXy5EWgE1LYhu5NzoAL' pub_key_addr = '2NCrvwAoL7fc8p5bVaqkbXWUmDStvTUBZAb' data = b'We have had success with the even public key' encrypted = attmpt4_alg(pub_key, data) sk = Key(priv_key) decrypted = ecies.decrypt(sk._pk.secret, encrypted) assert data == decrypted print(decrypted)
def attmpt4_odd_pub_key(): from bit import Key pub_key = '035178ab67471945e966833ffe3c4f6ad8fbac6c2f79c1df80a6ab9686dfb70fde' priv_key = 'cSQh7Ve5YbKptjECW6gMtdhX9v4N1AiN7ypZ22RWBSN31RpkcAsY' pub_key_addr = '2N3qAgYYwv1mJGksATbqzfsJ5LoAxcoCR9J' data = b'We have had success with the odd public key' encrypted = attmpt4_alg(pub_key, data) sk = Key(priv_key) decrypted = ecies.decrypt(sk._pk.secret, encrypted) assert data == decrypted print(decrypted)
def try_receive_verification_nonce(self, verification_receipt, account_index): """ try to receive a verification Args: verification_receipt [bytes]: the raw receipt received from an VerificationTxEvent Returns: pre_transfer_tx [int], nonce [bytes] """ privkey = self.addr2key[ self.w3.eth.accounts[account_index]]["private_key"] try: data = decrypt(privkey, verification_receipt) except Exception: return None, None pre_transfer_index = Web3.toInt(data[0:32]) return pre_transfer_index, data[32:]