MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by Matuno on 26 Dec 2013

This question is closed and may reopen in the future if edited.

I am trying to implement an RC4 implementation in Matlab. I want to encrypt a message (e.g. 'encrypt12') with a key(e.g. 'key'). I got the key stream but didn't get the ciphertext. I have been trying for many days to use many options for the xor but nothing seems working. My code:

C code:

#include <string.h>

unsigned char S[256]; char has[512];

#define S_SWAP(a,b) do { int t = S[a]; S[a] = S[b]; S[b] = t; }

void rc4(char *key, char *data){ int i,j; for (i=0;i<256;i++){ S[i] = i; } j = 0; for (i=0;i<256;i++){ j = (j+S[i]+key[i%strlen(key)]) %256; S_SWAP(S[i],S[j]); }

i = j = 0; for (int k=0;k<strlen(data);k++){ i = (i+1) %256; j = (j+S[i]) %256; S_SWAP(S[i],S[j]); has[k] = data[k]^S[(S[i]+S[j]) %256]; } has[strlen(data)+1] = '\0'; }

Matlab code:

if true function ef = rc4 (pf,k) sc = rc4key(k); j0 = 0; i0 = 0; for s0 = 1:length(pf) [r, i0, j0, sc]=rc4out(i0, j0, sc); for i = 1:length(pf), v(i)=double(pf(i))-48; end C = bitxor(v,r); data_show =dec2hex(C); ef = data_show; end

function sc=rc4key(key) le = length(key); sc = 0:255; j0 = 0; % scramble the key schedule for i0 = 0:255 k0 = floor(key( floor(mod(i0,le))+1 )); 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; ra = mod(sc(i0+1) + sc(j0+1), 256);%(S[i]+S[j]) %256 r = sc(ra);%S(S[i]+S[j]) %256

what I am expecting: Suppose I tried 'Hello' as data and 'hi' as key. then the C and in online RC4 [http://rc4.online-domain-tools.com/] it should come like this: 55aadb210b but I am getting very strange: 09242D2D2E.

*No products are associated with this question.*

## 0 Comments