1

下面的程序是从另一个 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....

4

1 回答 1

2

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

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

于 2014-01-09T09:41:16.067 回答