From: Brian Candler Date: 2008-10-24T16:37:10+09:00 Subject: Re: Big endian convention in Ruby Ashrith Barthur wrote: > The thing is the code perfectly.. works but my shasum is not the say > that I am supposed to get.. well thats the issue... Then it's not working perfectly, is it? OK, there's tons wrong with this code. I'm not going to debug it fully for you, as you need to do this yourself as a learning experience. I suggest you debug it by putting lots of debugging statements in, e.g. puts "h0 = #{h0.inspect}" and comparing the values in your code at each point as it runs with those in mine. However, the following glaring errors stand out just from a visual inspection: > while (newbitlength<=61) do I think this should be <56 (448 bits) > message << (('%016X' %(bit*8)).hex) Wrong expression: you have converted bit*8 to a hex ascii string, then converted it straight back to decimal!!! So this is identical to message << (bit * 8) which will append one character to the message. I suggest adding a check at this point to see that the padded message is exactly a multiple of 64 bytes long, because with your code I don't think it is, but this is a requirement for the rest of the algorithm to proceed. > for i in (0..79) > message<<'00'.hex > end Nowhere in the algorithm does it say add 80 zero bytes to the end of the message. > message.unpack('H8'*80) This is a bizarre unpack operation on the message. But not only that, you have not assigned the result to anywhere - so this line doesn't do anything at all! > a=h0 > b=h1 > c=h2 > d=h3 > e=h4 All the code from this point should be inside a loop, one iteration for each 64-byte block of the message (as the pseudocode says: "break message into 512-bit chunks // for each chunk") > for i in (0..79) > if (i>=16 or i<=79) then > message[i]=(((message[i-3]) ^ (message[i-8]) ^ > (message[i-14]) ^ (message[i-16]))<<1) > tempmessage=(message[i])>>31 > message[i]=(message[i]<<1)+tempmessage > end The pseudocode says: "break chunk into sixteen 32-bit big-endian words w[i], 0 ��� i ��� 15", but you have not done this. So in your code, message[i] is a single byte, message[0] to message[63], but actually you should have converted this to w[0] to w[15], each element of w comprising 4 bytes from the original message. > puts "The value of H0:"<