Trying to implement the cipher "Grasshopper" in Java. But there was a problem. C ++ has a function that I just don’t know how to implement in Java. The following is my implementation, but the compiler does not like operations with &.

char mul_gf256(char x, char y) { char z = 0x0; while (y) { if (y & 0x01) z ^= x; x = (x << 0x01) ^ (x & 0x80 ? 0xC3 : 0x00); y >>= 1; } return z; } 

Implementing on c ++ you can look at the github https://github.com/mjosaarinen/kuznechik/blob/master/kuznechik_128bit.c

    1 answer 1

    The compiler does not like bitwise operations with the сhar type (more precisely, at the end, since char not suitable for this task)

    The equivalent of a single-byte char - with a range of -128..127 in Java is byte

    (while in Java сhar two-byte 0..65535 )

    Here is the code brought to the compiled state (I did not check the correctness).

     byte mul_gf256(byte x, byte y) { byte z = 0x0, first, second; while (y!=0) { if ((y & 0x01) !=0) z ^= x; first = (byte) (x << 1); if (x < 0) second = -61; else second = 0; x = (byte) ((first) ^ (second)); y >>= 1; } return z; } 

    Although arithmetic can be performed with char , in most cases the type is raised to int, so a type conversion is required when assigning the result to char .

     char a, b, c; a = 'A'; a++; b = (char)(a+1); c = (char) (a & b); 
    • In C ++, byte is also original. In char, I already translated it for someone's recommendation. However, if you use byte, the error remains the same. That's the problem. - coolbober
    • @coolbober, in C ++ there is no byte type. Generally absent. If you come across a type byte , then somewhere above there is something like typedef unsigned char byte . - freim Nov.
    • byte in java also expands to int , and since it is signed, y >>= 1; may not zero y never. In the implementation of Bouncy Castle to deal with this in the cycle there is a counter. Kmk is easier to make local variables int , cast the method arguments to int via a & 0xFF and finally give the result. I do not know how it will be in speed. - zRrr
    • @zRrr Yep, I didn't pay attention to the right shift. y = (byte) ((y & 0xFF)>>1); will solve the problem? - MBo
    • @Mbo yes. initial approach with char also works - zRrr