Info
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
Ciphertext is not as desired for RC4 in Matlab
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (0개)
이 질문은 마감되었습니다.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!