【问题标题】:How do you offset a byte by an int in solidity?你如何在solidity中用一个int偏移一个字节?
【发布时间】:2017-12-22 17:45:33
【问题描述】:

我目前正在尝试以稳固的方式偏移字节以实现简单的凯撒密码解密。但是,我无法弄清楚如何做到这一点。这是我当前的代码,它在 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
}

但是,这给了我以下错误:

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;
                              ^----------------------------^

谢谢!

【问题讨论】:

  • “key”在哪里定义?
  • 对,key在函数参数中定义为int!我会更新帖子——对此感到抱歉。
  • 所以显示的算法不是凯撒密码的算法,因为您没有按照问题中的建议按索引计数移动字节。

标签: ethereum solidity smartcontracts ether


【解决方案1】:

就像 Damian Green 所说,我对您尝试编写的算法有点困惑,但下面的合约将解密 Caesar 加密文本。您应该能够根据需要对其进行修改。 (请原谅懒惰的 ASCII 值硬编码)。

请注意,您不能使用bytes32,因为它在 Solidity 中被视为特殊数组并且是只读的。参见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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    相关资源
    最近更新 更多