【问题标题】:RSA code in matlabmatlab中的RSA代码
【发布时间】:2012-03-15 05:34:15
【问题描述】:

我想加密 '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

d

加密过程的输出

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

德基 =

 1

phi_n =

 6

len =

28

密码文本 =

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

解密过程

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

【问题讨论】:

  • 您发布的代码不完整。 “无法正常工作”是什么意思?
  • 尝试使用现有的hackchina.com/en/cont/49303
  • 这和Java有什么关系?
  • @phonon 请看加密后的输出
  • @cheery 代码在 java 中。如果可能的话,我希望该代码在没有 java 帮助的情况下在 matlab 中运行。

标签: matlab encryption rsa public-key-encryption


【解决方案1】:

不要费心自己实现它。编写加密货币很困难,并且错误会带来安全后果。使用来自受信任供应商的知名库。

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

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多