Best way to perform UInt32 additions in VB.NET that are supposed to overflow

Viewed 75

While trying to write the ARX part of the ChaCha20 encryption algorithm in VB.NET, I run in to the issue of overflow exceptions during the addition part.

There are many additions of UInt32 numbers in the algorithm, and numbers are supposed to overflow during addition, but in other parts of my code I want to catch these exceptions.

One way of dealing with this and avoid overflow exceptions completely is to interim-convert to UInt64 and then do the additions this way:

a = (a + b) mod 2^32

I won't get any overflows but this doesn't work with the circular bit rotations needed for an ARX algorithm as I'm now pushing bits in to the empty 32 bits in the 64 bits UInt.

This converting back and forth is making the algorithm slower, and per 512 bits data block we are going through 20 rounds of a set of calculations so performance of this part of the code is pretty important.

Is there a more elegant way to deal with this in VB.NET?

More info about the algorithm: https://en.wikipedia.org/wiki/Salsa20

Thank you for sharing your insights!

1 Answers

You can turn overflow checking off per compiled assembly:

enter image description here

So it means you can have a DLL where you do all your overflowing math, and that DLL project has this tickbox checked (overflow checking is off)..

..but your main project that needs to do math with overflowing ON, does NOT have this option set in its own compilation settings

Here my OverflowOff project is a DLL that has "remove checks" enabled. A method has provided int maxvalue overflowed to int minvalue, then the forms project that uses the DLL has crashed with overflow because its own compile settings are set to perform overflow checks:

enter image description here

Related