0

I need to write down methods to encrypt and decrypt string messages using contract private | public keys in a smart contract. However you may think it's dangerous or anything else, the question is: Is it possible to use a smart contract private key inside it's methods to encrypt or decrypt data?

This is a short and simple example. I need to implement the encode/decode inside the methods.


contract Secret {
    function encode(string memory message) public returns (string) {
        // ...implementation
    }
    function decode(string memory message) public returns (string) {
        // ...implementation
    }
}

1
  • Leaving security considerations aside. The EVM is a constrained environment, so many thing you may take for granted are hard to achieve or too costly. It is possible to write an implementation of secure algorithms like AES, but it will be too expensive to execute.
    – Ismael
    Aug 1, 2022 at 14:01

1 Answer 1

1

I'll start off by saying that there is nothing private or hidden in a smart contract. Even if we use the keyword private for some of our state variables, they are publicly seen in the blockchain.

So, you could manage to import your own private and public keys to a smart contract and encrypt and decrypt messages, but everyone would be able to see your private/public keys, and your keys and the funds locked to them would be compromised.

Smart contracts don't have private keys of their own, so you cannot use a smart contract's private key because it doesn't exist.

Alternatively, you could use a public key to encode a message and use a private key off-chain to decrypt it.

But anyways, I don't recommend trying to encrypt or decrypt messages in a smart contract.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.