I am trying to create a solidity contract that decrypts a message using the an AES key. The data to be decrypted is saved as a variable in the contract (this data is already encrypted). The user should be able to pass an AES key into the decrypt function, this function should decrypt and return the message.
I do not mind the key being exposed on the network. Would there be any way to achieve this?
Solidity currently (v0.8) doesn't support any of the AES algorithms.
If your goal is to perform an action (e.g. transfer funds) to a user providing the correct key, you could have them calculate a keccak256
(one-way) hash of some secret (e.g. the key) off-chain, and then submit the original key for validation (against the hash stored in the contract).
pragma solidity ^0.8;
contract MyContract {
// keccak256 hash of the string "foo"
bytes32 hash = 0x41b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d;
function guessThePassword(string memory _password) external view returns (bool) {
return keccak256(abi.encodePacked(_password)) == hash;
}
}
Mind that this approach (as well as your original approach from the question) is vulnerable to frontrunning. One of the ways to prevent frontrunning, is to use double hashing. You can see a code example in this contract that was used for a competition type "first submitting the correct password can withdraw funds".