简体   繁体   中英

Wrong result from mod integer ( mod 256 ) but get negative

I have a function to make RC4 Sbox.

public void initRC4(byte[] Key){
        byte tmp = 0;
        for(int i = 0; i< 256;i++){
            S[i] = (byte) (0xFF & i);   
        }      
        for(int j = 0 , i = 0; i< 256; i++){
            j = ((j + S[i] + Key[i % Key.length] ) % 256) ;
            System.out.println(Integer.toBinaryString(j) +" "+ j);
            tmp = S[j];
            S[j] = S[i];
            S[i] = tmp;
        }
    }

So my Input to this function is getByte[] this String "This is first line" .But I got an exception java.lang.ArrayIndexOutOfBoundsException: -62 .And my final line was 11111111111111111111111111000010 -62 . What did I do wrong ?

S[i] is a byte, which has a value range of -128 to +127 , ie it can be a negative number.

This means that the expression j + S[i] + Key[i % Key.length] can be negative, and a negative number % 256 is also a negative number, so j may end up negative.

This will cause S[j] to throw ArrayIndexOutOfBoundsException .

The simplest solution would be to replace % 256 with & 0xFF .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM