有趣的按位操作

时间:2015-01-21 05:45:31

标签: c sha1 bitwise-operators

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

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

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

2 个答案:

答案 0 :(得分:2)

在某些计算机上,int(因此也unsigned int)可能是64位类型。掩码是int是32位类型的机器上的无操作,但对于64位类型的机器则很关键。当编译器没有任何用处时,编译器将知道并优化操作。

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

答案 1 :(得分:2)

SHA1的reference implementation,在评论中有以下注释:

/*
 *  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.
 *
 */

在SHA1的这个实现中,Portability Issues就是这种操作的情况,它允许它在int s更大的机器上正常运行。