How to encrypt information in custom_json [episode 1]

in #blockchain4 years ago

Custom json operations are used every day from dapp to manage informations about their users and to store them in a decentralized way in the steem or `hive' blockchains.

In my opinion this is a very powerful tool that these blockchains and the new blurt as well, to implement a new way to manage users in a public ledger, reducing back end costs, like database management and server expenses.

Thinking about this concept I stumble upon a problem, what if you wish to store in the public blockchain sensible data like users email for example.

The solution is to encrypt the informations and in order to hide them while saving them in the blockchain.

To solve this problem I wrote a few lines of python code as a proof of concept.

At the beginning we need to import the libraries to work with:

from beem import Steem
from beem.account import Account
from cryptography.fernet import Fernet

The last line from cryptography.fernet import Fernet, is our way to hide the info in the blockchain.

Now lets create with Fernet our key to be able to encrypt and decrypt the info.

def generate_key():
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

In this case the key is saved in the same directory of the code in a file named secret.key.

Let's pass the information about the user that is going to broadcast the custom_json operation in the blockchain, for this example we are using the steem blockchain but the same thing can be done on hive with the same code.

stm = Steem("https://api.steemit.com", keys=['YOUR POSTING KEY'])
acc ="YOUR ACCOUNT NAME"

Now let's broadcast the custom_json

def transaction():
    key=load_key()
    secret='super secret message'.encode()
    fer=Fernet(key)
    secret=fer.encrypt(secret)
    secret=secret.decode('utf_8')
    data = {"secret":secret, "version" : "0.01"}
    stm.custom_json("test_DM", data, required_posting_auths=[acc])
transaction()

As you can see this operation required the posting authority so it is necessary to use just the posting key.
The message to encrypt is: super secret message

Here you can check it in the steem blockchain:

txid: https://steemworld.org/block/44871043/ab5ce3554d2815121d5369dd75fd632871f56113?login=digitalmine.app

test_DM.png

AS you can see the message is encrypted and just who have the key can read the content.

In the next episode I'll write bout how to actually decode the message and read its content.