0

I am new to matlab programming and trying to work with RC4 code [source:http://www.cryptosmith.com/archives/621]. I am trying to get a message encrypted with a key but after getting key stream I am stuck while doing xor of the data. I probably am making mistakes in several places as my result is showing 0 all through. The make function code I am having problem is:

function w = rc4make(n,k)
% rc4make - makes a vector of "n" RC4 outputs of key "k"
sc = rc4key(k);
l = [];
j0 = 0;
i0 = 0;

for s0 = 1:n 
    [r, i0, j0, sc]=rc4out(i0, j0, sc);
    l =[l r];
    L1 = logical(n);
    disp(L1);
    L2 = logical(l);% converting into logical array 
    disp(L2);
    w = xor(L1,L2);
end

function sc=rc4key(key)
% rc4key - return key schedule array for key k
% SEEMS BROKEN - bytes 2-9 are swapped with other key schedule bytes
% At best, not compatible with 'real' RC4. At worst, also more vulnerable

% set up the array
le = length(key);
sc = 0:255;
j0 = 0;

% scramble the key schedule
for i0 = 0:255
    k0 = floor(key( floor(mod(i0,le))+1 ));%floor rounds the number into round figure
    j0 = floor(mod( j0 + k0 + sc(i0+1), 256));
    tm = sc(i0+1);
    sc(i0+1) = sc(j0+1);
    sc(j0+1) = tm;
end

function [r, i0, j0, sc]=rc4out(i0, j0, sc)
% next byte of rc4 output
% inputs: i0, j0 = indices; sc = key schedule
% outputs: r=random byte; i0, j0 = indices; sc = key schedule

%for q=0:strlen(data)
i0 = mod( (i0+1), 256);
j0 = mod( j0 + sc(i0+1), 256);
tmp = sc(j0+1);
sc(j0+1) = sc(i0+1);
sc(i0+1) = tmp;
r = mod(sc(i0+1) + sc(j0+1), 256);%(S[i]+S[j]) %256

The function I am calling is: rc4make(12,'hi') where 12 is the plaintext and hi is the key. Could you please guide me to understand my code's problem and please suggest to get the ciphertext properly.

Ray
  • 2,472
  • 18
  • 22
  • Not sure what you are trying to do but I think your loop is not set up correctly. The n value appears to be a constant, l is appears to be always empty. The r value appears to never be used. Finally you probably don't want to use "logical" unless you attempting to reference a matrix. – TallBrianL Dec 09 '13 at 05:01
  • Thank you for your comment. I am using 12 as n and I inserted value of l now. I put whole code for your better understanding. I didn't understand your last line as I read somewhere that I can't xor without converting it to logical array. Thanks again. – user2979041 Dec 09 '13 at 05:16
  • What is the expected value / meaning of L1 and L2. What are the expected dimensions? – TallBrianL Dec 09 '13 at 05:23
  • My desire result should come like this: 2c fd, which I know probably need more things to do in that above code. – user2979041 Dec 09 '13 at 06:00
  • You might want to apply `bitxor` on an integer-valued array rather than `xor` on a logical array. – Cris Luengo May 06 '18 at 15:10

0 Answers0