0

I'm currently trying to offset bytes in solidity to implement a simple Caesar cipher decryption. However, I can't figure out how to do this. Here is my current code, which gives a few compiler errors in Remix:

function decrypt(bytes32 data, int key) public returns (bool) {
    bytes32 decryptedData = data;    // `data` here is the encrypted data
    // decryption
    for (int i = 0; i < decryptedData.length; i++) {
        decryptedData[i] = (decryptedData[i] - key) % 256;
    }
    // returns if sha256(decryptedData) matches some value
}

However, this gives me the following errors:

TypeError: Expression has to be an lvalue.
            decryptedData[i] = (decryptedData[i] - key) % 256;
            ^--------------^

TypeError: Operator - not compatible with types bytes1 and int256
           decryptedData[i] = (decryptedData[i] - key) % 256;
                               ^--------------------^

TypeError: Operator % not compatible with types bytes1 and int_const 256
           decryptedData[i] = (decryptedData[i] - key) % 256;
                              ^----------------------------^

Thanks!

aevumcessi
  • 61
  • 8

1 Answers1

0

Like Damian Green said, I'm a bit confused on the algorithm you're trying to write, but the contract below will decrypt a Caesar encrypted text. You should be able to modify it for your needs. (Please excuse the lazy hard-coding of ASCII values).

Note that you can't use bytes32 as that is treated as a special array in Solidity and is read-only. See "index access" section of http://solidity.readthedocs.io/en/develop/types.html#fixed-size-byte-arrays

pragma solidity ^0.4.17;

contract CaesarDecryption {
  function decrypt(bytes data, int key) pure public returns (bytes) {
      bytes memory decryptedData = data;

      for (uint i = 0; i < decryptedData.length; i++) {
          decryptedData[i] = decryptByte(decryptedData[i], key);
      }

      return decryptedData;
  }

  function decryptByte(byte b, int k) pure internal returns (byte) {
      uint8 ascii = uint8(b);
      uint8 asciiShift;

      if (ascii >= 65 && ascii <= 90)
        asciiShift = 65;
      else if (ascii >= 97 && ascii <=122)
        asciiShift = 97;

      return byte(((ascii - asciiShift - k + 26) % 26) + asciiShift);
  }
}
Adam Kipnis
  • 10,175
  • 10
  • 35
  • 48