A while back I wrote a conversion of RFC 1321 (RSA Data Security’s Message-Digest Algorithm for C) to ASPECT script.  During this conversion I discovered that the C code that was used to generate a rotate no carry bit-shift did not work as intended.  (In the RFC they refer to it as circularly shifting.)

Back then Wikipedia didn’t have an article on bitwise operations and I did not have the access to mathematic books.  I was doing some coding this last weekend and found an irregularity which I have still not successfully reproduced or explained, and while doing research on the matter, I came across the bitwise operation article at Wikipedia and discovered why ASPECT does not work as intended:

The reason for this is that C uses a logical shift whereas ASPECT uses an arithmetic shift.  This plays havoc with RFC 1321 and as such I had to do some mathematical tinkering to get an arithmetic shift to behave like a logical shift, which allows for the creation of a rotate no carry shift.

This is the code that comes from RFC 1321

#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))

This is the resultant code with the arithmetic to logical shift conversion code:

func ROTATE_LEFT : integer
 param integer x, n
 integer z
 z = (x >> (32-n)) & ~(0×80000000 >> (31-n))
 return ( (x << n) | z )
endfunc

In order to reduce compiler and stack overhead, this could probably be shorted to a #define that looks like this (I haven’t tested this):

#define ROTATE_LEFT(x,n)  ( (x << n) | (x >> (32-n)) & ~(0×80000000 >> (31-n)) )

In summary you replace

((x) >> 32-(n))

with

 (x >> (32-n)) & ~(0×80000000 >> (31-n))

This causes the arithmetic shift to operate like a logical shift if the sign bit is set to 1 (which is the only time an arithmetic and logical shift operate differently).  I posted a bit of source to my script page which demonstrates this “bug” and the fix.

NOTE: A circular shift (or rotate no carry shift) is not inherent in either C source or ASPECT, hence the creation of the ROTATE_LEFT function in ASPECT source (or the compiler #define in C source)

Merry Christmas

   

Favorite Books

Favorite Music

© 2011 Undecided Suffusion theme by Sayontan Sinha