Porting SHA512 and learning Motoko along

I blogged my experience getting started with Motoko while porting SHA512 to it.


Nice. Thank you for the contribution!

Regarding the 128 bit numbers, the only place where you need that is when the message length is encoded as part of the padding at the end of the message, right? I mean, there is no arithmetic needed for those kind of numbers, you only need to encode one such number to bytes it seems.

Yes. It’s only that the existing SHA256 implementation depends in intermediate arithmetic on data lengths (incoming and processed) being 64 bit numbers . One example is how it determines how many full blocks are ready to be processed: sha256:L87. And so I replaced NatX-dependant computations with something equivalent (hopefully not on the expense of cost).

Technically speaking I could have also just left all lengths as Nat64 and finally encoded as 128 bits since I guess practically no one is going to hash that amount of data. But then it wouldn’t exactly conform to SHA512.

I see, makes sense as you say, to track the length as Nat instead of Nat64 while write() calls happen and then convert to 128 bits in the end.

There is now an implementation of the whole SHA2 family (all algorithms): GitHub - timohanke/motoko-sha2: Sha2 family in Motoko