2

Is there a way to do basic decryption in Solidity?

For example:

Given 3 actors and message:

  1. Server
  2. Client
  3. Solidity contract

The flow:

  1. Server generates message and signs with private key
  2. Client uses the message as parameter to call contract
  3. Contract uses server's public key to decrypt the message (make sure it came from server)

Is there a way in Solidity to do "decrypt" a string using a pubkey?

2 Answers 2

2

Your looking for signature verification, not decryption.

Yes, notably, Solidity includes a function ecrecover that can recover the account that signed a message.

For details about how to use this to sign and verify messages, see https://programtheblockchain.com/posts/2018/02/17/signing-and-verifying-messages-in-ethereum/.

0

If you have a signature and the message that was signed, you can get the address that signed the message using the ecrecover function in Solidity.

It is explained in this tutorial.

You need to split the signature into 3 parts like this:

const signature = "0x...."

const r = signature.slice(0, 66);
const s = "0x" + signature.slice(66, 130);
const v = parseInt(signature.slice(130, 132), 16);

And then in Solidity you can verify the signature like this:

function verify(bytes32 _data, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
    bytes memory prefix = "\x19Ethereum Signed Message:\n32";
    bytes32 hash = keccak256(abi.encodePacked(prefix, _data));
    address signer = ecrecover(hash, _v, _r, _s);
    return signer;
}

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.