How to encrypt information in custom_json [episode 2]

in #steem4 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.