【问题标题】:Interesting bitwise operation有趣的位运算
【发布时间】:2015-03-19 13:41:29
【问题描述】:

我今天在审查 C 中的 SHA1 实现时遇到了一些相当有趣的代码。

temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
temp &= 0xFFFFFFFF;

我觉得有趣的部分是temp &= 0xFFFFFFFF;。请注意,temp 已被声明为 无符号整数。这个操作不会没有效果吗?我唯一能想到的是设计者试图强制使用 32 位整数,但这不会在编译时完成吗?
我很想知道人们的想法。

【问题讨论】:

  • temp确切类型是什么?
  • 在某些机器上,int(或unsigned int)可能是 64 位类型。掩码在 int 是 32 位类型的机器上是无操作的,但在它是 64 位类型的机器上是关键的。当它没有做任何有用的事情时,编译器会知道并优化操作。

标签: c sha1 bitwise-operators


【解决方案1】:

在某些机器上,int(因此也有unsigned int)可能是 64 位类型。掩码在 int 是 32 位类型的机器上是无操作的,但在它是 64 位类型的机器上是关键的。当它没有做任何有用的事情时,编译器会知道并优化操作。

另外,曾经有36-bit int types的机器和60-bit int types的其他机器;在这样的机器上也很重要。

【讨论】:

    【解决方案2】:

    SHA1的reference implementation,在cmets中有如下注释:

    /*
     *  sha1.c
     *
     *  Description:
     *      This file implements the Secure Hashing Algorithm 1 as
     *      defined in FIPS PUB 180-1 published April 17, 1995.
     *
     *      The SHA-1, produces a 160-bit message digest for a given
     *      data stream.  It should take about 2**n steps to find a
     *      message with the same digest as a given message and
     *      2**(n/2) to find any two messages with the same digest,
     *      when n is the digest size in bits.  Therefore, this
     *      algorithm can serve as a means of providing a
     *      "fingerprint" for a message.
     *
     *  Portability Issues:
     *      SHA-1 is defined in terms of 32-bit "words".  This code
     *      uses <stdint.h> (included via "sha1.h" to define 32 and 8
     *      bit unsigned integer types.  If your C compiler does not
     *      support 32 bit unsigned integers, this code is not
     *      appropriate.
     *
     *  Caveats:
     *      SHA-1 is designed to work with messages less than 2^64 bits
     *      long.  Although SHA-1 allows a message digest to be generated
     *      for messages of any number of bits less than 2^64, this
     *      implementation only works with messages with a length that is
     *      a multiple of the size of an 8-bit character.
     *
     */
    

    Portability Issues 是此 SHA1 实现中此操作的情况,它允许它在具有较大 ints 的机器上正常运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多