shr*_*ree 7 encryption matlab rsa public-key-encryption
我想加密诸如'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
Run Code Online (Sandbox Code Playgroud)
加密过程
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
Run Code Online (Sandbox Code Playgroud)
d
输出加密过程
k =
0 1 1 0 1 0 1 0 0 0
Run Code Online (Sandbox Code Playgroud)
prime_mat =
2 3 5 7
Run Code Online (Sandbox Code Playgroud)
p =
7
Run Code Online (Sandbox Code Playgroud)
q =
2
Run Code Online (Sandbox Code Playgroud)
n =
14
Run Code Online (Sandbox Code Playgroud)
enckey =
5
Run Code Online (Sandbox Code Playgroud)
deckey =
1
Run Code Online (Sandbox Code Playgroud)
phi_n =
6
Run Code Online (Sandbox Code Playgroud)
len =
28
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
解密过程
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)]
Run Code Online (Sandbox Code Playgroud)
UINT8(plain_text);
And*_*nke 11
不要打扰自己实施它.编写加密很困难,错误会带来安全隐患.使用来自可信赖供应商的知名库.
在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'))'
Run Code Online (Sandbox Code Playgroud)