2014-01-09 86 views
1

下面这个程序是从另一个C程序转换而来的。函数rc4key显示正确的结果,但功能prga显示不正确的结果(与C,正确的程序相比),我想了很长时间,但不明白为什么j0显示178,255,255,255,255而不是178,174,22,42,76。您的建议和意见非常需要。我用RC4( '你好', '您好')在此功能:Matlab程序在一个函数中显示不正确的结果

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 ....

回答

2

您的问题lem是你把你的数据转换成uint8。 Matlab的不加这样这些:255 + 1 => 255

快速和肮脏的解决办法:注释掉行:s = uint8(s);