Matlab program is showing incorrect result in one function

614 views Asked by At

This below program is a converted version from another C program. Function rc4key is showing correct result but function prga is showing incorrect result (comparing to the C, the correct program), I am trying for quite long time but can't understand why the j0 is showing 178, 255, 255, 255, 255 instead of 178, 174, 22, 42, 76. Your suggestion and input is very much needed. I used rc4('Hello','Hi') in this function:

function ef = rc4(pf,ki)%Please ignore this function for this time being
s = rc4key(ki);
disp(s);
s = uint8(s);
j0 = 0;
i0 = 0;
r = prga(s, pf);
disp(r);
v = uint8(pf);
C = bitxor(v,r);
disp(C);
data_show = dec2hex(C);
ef = data_show;

function sc=rc4key(key)%This function is showing correct result
le = length(key);
sc = 0:255;
j0 = 0;
% scramble the key schedule
for i0 = 0:255
    k0 = floor(mod( key( floor(mod(i0,le))+1 ), 256));
    j0 = floor(mod( j0 + k0 + sc(i0+1), 256));
    disp(j0);
    tm = sc(i0+1);
    sc(i0+1) = sc(j0+1);
    sc(j0+1) = tm;
end

%This function is showing incorrect result in below mentioned section
function r = prga(sc, data)
i0=0; j0=0; x=[]; t=[];
for x=0:length(data)-1%upto this ok
    i0 = mod( (i0+1), 256);%upto this ok
    disp(sc(i0+1));%this shows 178, 252, 104, 20, 34 which is correct value


    %j0 = j0 + sc(i0+1);%This also shows incorrect value as below (i.e.178, 255, 255, 255, 255)
    j0 = mod( j0 + sc(i0+1), 256);%It should show: 178, 174, 22, 42, 76
    %whereas j0 is showing 178, 255, 255, 255, 255
    disp(j0);


    tm = sc(i0+1);
    sc(i0+1) = sc(j0+1);
    sc(j0+1) = tm;
    r = sc(j0+1);%Not crucial for this time being
    %r(x+1) = sc(mod( sc(i0+1) + sc(j0+1), 256)+1);
end

I am expecting: The j0 should show: 178, 174, 22, 42, 76 whereas j0 is showing 178, 255, 255, 255, 255.

What I have tried so far: I have tried to change the value of sc in rc4key function, checked only the prga function in separate worksheet - This shows correct result that time, But when I am trying for full program (which is necessary) it is showing that 255, 255....

1

There are 1 answers

0
bdecaf On BEST ANSWER

your problem is that you cast your data to uint8. Matlab does the addition like this for these: 255+1 => 255

Quick and dirty fix: Just comment out the line: s = uint8(s);