How to encrypt information in custom_json [episode 2]

in #hive5 years ago

Continuation of this post:

Now we are going to retrieve the encrypted message from the blockchain, and decrypt it for our usage.

The script I'm going to use is in python like the previous one, and it will parse each single block to check if there is a custom_json with our id in order to get the message. so let's start to import the libraries

from beem.blockchain import Blockchain
from beem import Steem
from beem.nodelist import NodeList
import re
from cryptography.fernet import Fernet
nodelist = NodeList()
nodelist.update_nodes()

After that we need to load the Fernet key we saved before in order to decrypt the message.

def load_key():
    """
    Loads the key named `secret.key` from the current directory.
    """
    k=open("secret.key", "rb").read()
    return k
key = load_key()
f = Fernet(key)

Let's start the blockchain instance for this example we will use the steem blockchain, but it works as well for the hive one.

stm = Steem(node=nodelist.get_steem_nodes())
b = Blockchain(blockchain_instance=stm)

Now let's start an infinite loop to keep check the blocks, and print out the message once found in the blockchain.

for i in b.blocks(start=b.get_current_block_num()):
    print (i['id'])
    for t in i['transactions']:
        for o in t['operations']:
            if o['type']=='custom_json_operation':
                if o['value']['id']=='test_DM':
                    enc= re.findall('"type":"(.+?)"',o['value']['json'])[0]
                    ms=enc.encode('utf_8')
                    decrypted_message = str(f.decrypt(ms))
                    print (decrypted_message.replace("b'",'').replace("'",''))

Normally it takes around a minute from the custom_json publication to get discovered in the blockchain.

Sort:  

Thanks for sharing anorher tutorial nice tutorial about emcryption in python. Love to see that you share the link of part 1. It will be easier for python enthusiast to explore your nice efforts.

Your post has been submitted to be curated with @gitplait community account because this is the kind of publications we like to see in our community.

Join our Community on Hive