2012-02-24 18 views
6

Voglio crittografare un messaggio come 'HELO1234 e quindi decrittografare per ottenere quello originale. Ho scritto il codice RSA in matlab che non funziona correttamente.Codice RSA in MATLAB

PARAMETRI CALCOLO

temp=1; 
range=1:10; 
k=isprime(range) 
prime_mat=range(find(k)) 
p=randsample(prime_mat,1); 
q=randsample(prime_mat,1); 
if(p~=q) 
n=p*q; 
phi_n=(p-1)*(q-1); 
u=1:phi_n -1; 
end 
while temp 
enckey=randsample(u,1); 
    deckey=randsample(u,1); 
    if(enckey~=deckey) 
    if(gcd(enckey,phi_n)~=1 ... 
    && gcd(deckey,phi_n)~=1 ... 
    &&gcd(enckey*deckey,phi_n)~=1) 
    temp=1; 
else 
temp=0; 
    end 
    end 
end 

CRIPTATURA PROCESSO

char t= 'hello123'; 
     t=uint8(t); 
     len=length(t) 
     pow=[]; 
     cipher_text=[]; 
      for i=1:len         
       pow=[pow;t(i).^(enckey)]; %each element of the pt matrix(plain text) is raised to the power of encryption key(enc_key) and stored in pow matrix(power matrix) 

    cipher_text=[cipher_text;mod(pow(i),n)];% cipher text is calculate 

d

USCITA DEL processo di cifratura

k =

0  1  1  0  1  0  1  0  0  0 

prime_mat =

2  3  5  7 

p =

7 

q =

2 

n =

14 

EncKey =

5 

deckey =

1 

phi_n =

6 

l en =

28 

cipher_text =

3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 
3 

DECRYPTION PROCESSO

plain_text=[]; 
pow1=[]; 
len1=length(cipher_text); 
for i=1:len 
    pow1=[pow1;cipher_text(i).^(deckey)] 
    plain_text=[plain_text;mod(pow1(i),n)] 

uint8 (plain_text);

+0

Il codice che hai postato è incompleto. E cosa intendi con "non funziona correttamente"? – Phonon

+1

Prova ad usare quello esistente http: // www.hackchina.com/en/cont/49303 – Cheery

+0

Cosa c'entra questo con Java? –

risposta

10

Non preoccupatevi di implementarlo da soli. Scrivere la crittografia è difficile e gli errori hanno conseguenze sulla sicurezza. Utilizzare una libreria ben nota di un fornitore affidabile.

In Matlab, è possibile richiamare le classi di crittografia Java standard incluse con la JVM in bundle con Matlab. Il codice Matlab sarà simile a questo.

import javax.crypto.Cipher; 

plaintext = 'foobar'; 

cipher = Cipher.getInstance('RSA'); 
keygen = java.security.KeyPairGenerator.getInstance('RSA'); 
keyPair = keygen.genKeyPair(); 
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); 

plaintextUnicodeVals = uint16(plaintext); 
plaintextBytes = typecast(plaintextUnicodeVals, 'int8'); 
ciphertext = cipher.doFinal(plaintextBytes)' %' 

% And back out 
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic()); 
decryptedBytes = cipher.doFinal(ciphertext); 
decryptedText = char(typecast(decryptedBytes, 'uint16'))'