matlab - matlab中的RSA代码

标签 matlab encryption rsa public-key-encryption

我想加密诸如'HELO1234之类的消息,然后解密以获得原始消息。我在 matlab 中编写了 RSA 代码,但无法正常工作。

PARAMETER CALCULATION

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

ENCRYPTION PROCESS

 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

OUTPUT OF encryption process

k =

 0     1     1     0     1     0     1     0     0     0

prime_mat =

 2     3     5     7

p =

 7

q =

 2

n=

14

加密 key =

 5

装饰=

 1

phi_n =

 6

长度=

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

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(纯文本);

最佳答案

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

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

关于matlab - matlab中的RSA代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9436323/

相关文章:

MATLAB 矩阵替换赋值给出错误

c - 我的密码给我一个浮点异常,我不知道为什么?

java - 使用外部随机数源创建 RSA key (Java)

java - 如何在 JAVA 中为 RSAPrivateKey 使用密码?

javascript - Matlab 中/... 是什么意思?

matlab - 在 Simulink 中实现自定义 MATLAB 函数

excel - 每次循环后将信息写入 Excel

java - Blowfish 加密 - 在 php 和 java 中加密,我得到了不同的加密值

amazon-web-services - 数据如何在内部存储在 AWS DynamoDB 上?加密还是纯文本?

c++ - 在开源代码中对字符串进行签名