Matlab中的RSA代码

8

我想加密一条消息,比如'HELO1234',然后解密以得到原始消息。我已经在Matlab中编写了RSA代码,但它没有正确工作。

参数计算

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

加密过程

 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

加密过程的输出结果

加密后的密文

k =

 0     1     1     0     1     0     1     0     0     0

prime_mat =

 2     3     5     7

p =

 7

q =

 2

n =

14

加密密钥 =

 5

deckey =

 1

phi_n =

 6

长度 =

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 PROCESS

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类型。


你发布的代码不完整。而且你所说的“不能正常工作”是什么意思? - Phonon
1
尝试使用现有的http://www.hackchina.com/en/cont/49303 - Cheery
这与Java有什么关系? - Hunter McMillen
@ phonon 请查看加密过程后的输出。 - shree
这是用于生产代码,还是作为学习密码学背后的数学工作原理的练习? - Andrew Janke
显示剩余2条评论
1个回答

12

不要自己实现加密算法。编写加密算法很难,而且错误会导致安全问题。使用来自可信供应商的知名加密库。

在Matlab中,您可以调用与Matlab捆绑的JVM中包含的标准Java加密类。 Matlab代码大致如下。

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'))'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接