Matlab程序在一个函数中显示不正确的结果

时间:2014-01-09 08:23:22

标签: matlab rc4-cipher

以下程序是另一个C程序的转换版本。函数rc4key显示正确的结果,但函数prga显示不正确的结果(与C,正确的程序相比),我正在尝试很长时间,但无法理解为什么j0显示178,255,255,255,255而不是178,174,22,42,76。非常需要你的建议和意见。我在这个函数中使用了rc4('Hello','Hi'):

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

我期待: j0应显示:178,174,22,42,76,而j0显示178,255,255,255,255。

到目前为止我尝试了什么:我试图在rc4key函数中更改sc的值,仅检查单独工作表中的prga函数 - 这显示了正确的结果,但是当我尝试完整的程序(这是必要的)它显示255,255 ....

1 个答案:

答案 0 :(得分:2)

您的问题是您将数据转换为uint8。 Matlab为这些添加这样的加法:255 + 1 => 255

快速而肮脏的修复:只需注释掉该行:s = uint8(s);