Encrypting some data

Hi All !

I am new to flow.

I would like to store some informations in a String variable inside a resource, but i want to encrypt this data with a key (so i could decrypt it later) at resource creation and on-chain.
So i want to know if there is any functions (builtins ?) to encrypt data with a key ?

I cannot do it off-chain, it must be done on-chain.
If there are no solution i am planning on writing my own encryption algorithm or copy pasting some existing algorithms (does it sound good to you ?).

Thank you very much for your help !

Hi and welcome! The issue with encrypting something using an on-chain method is that that method will by nature be public (i.e. people can look up the contract at any time). So you can’t incorporate any secrets as properties. Even if the encryption key / secrets are passed in later, they could be inspected as transaction arguments for example. I would probably say it’s overall easier to encrypt the contents before writing to the chain, and then writing the encrypted contents to the chain (and likewise reading encrypted contents from the chain, and then decrypt it). That way there’s less risk of leaking keys/information throughout the transaction (e.g. arguments, output, etc) as the tx will only deal with encrypted data.

Having said that, for more information on what crypto functions are built in to Cadence, you can check out: Crypto | Flow Blockchain

Good luck!

Alright, thank you for your reply.

I think there are multiple methods available publicly without being a treat to the encryption algorithm itself, think of it like that: Blockchain uses a known algorithm (also source codes are public) to generate public and private keys, but you still cannot guess the private key from a public key. With the public key you can get A to B, but to do the opposite you need the private key (B to A) even though the encryption and decryption algorithms are public.

I looked for Crypto | Flow Blockchain but haven’t found anything to encrypt data. So i think i will be implementing some code into my smart contract to encrypt the data :confused: (shouldn’t be complicated as the encryption is basically just pow(X, e) mod n on each character. e and n being compositions of the public key)

I think it would be cool to have ‘encrypt’ and ‘decrypt’ functions in Crypto | Flow Blockchain what do you think ?