How can i implement Diffie Hellman Key exchange in Simulink using MATLAB function?
6 次查看(过去 30 天)
显示 更早的评论
i was trying to do this code in simulink using 2 MATLAB funcions but i keep getting errors.
how can i conver the code into MATLAB function ?
clc;%Clear command window
disp('Diffie Hellman Key Exchange');
disp('-----------------------------------------');
clear
close all;%Clear variables in workspace and close figure
%Input value of g and p, and ensure that g and p is prime
prime = 0;
while prime == 0
g = input('Enter a value for g: ');
p = input('Enter a Value for p: ');
pg = isprime(g);
pp = isprime(p);
if pg == 0
disp('g is not prime');
end
if pp == 0
disp('p is not prime');
end
prime = pg & pp;
end
disp('---Value For X---');
xa = randi([1 p-1]);%Calculate value of Xa
xb = randi([1 p-1]);%Calculate value of Xb
disp(['Xa is: ' num2str(xa)]);%Convert xa to string and display it
disp(['Xb is: ' num2str(xb)]);%Convert xb to string and display it
disp('---Value For Y---');
%Calculate value of Ya and Yb
ya = power(g,xa);
ya = mod(ya,p);
yb = power(g,xb);
yb = mod(yb,p);
disp(['Ya is : ' num2str(ya)]);%Convert ya to string and display it
disp(['Yb is : ' num2str(yb)]);%Convert yb to string and display it
disp('---The Shared Key---');
%Calculate shared key
ha = power(yb,xa);
ha = mod(ha,p);
hb = power(ya,xb);
hb = mod(hb,p);
disp(['Shared Key A: ' num2str(ha)]);%Convert ha to string and display it
disp(['Shared Key B: ' num2str(hb)]);%Convert bb to string and display it
0 个评论
回答(1 个)
Harsh Mahalwar
2024-2-28
Hi Elyazeya,
I can understand that you are trying to implement Diffie Hellman key exchange algorithm in MATLAB function block of Simulink.
Upon analysis, I observed that the existing code structure would require some modifications to align with the cryptographic standards and best practices of the Diffie-Hellman algorithm.
Here’s the revised implementation of Diffie Hellman key exchange that might suite your workflow better:
function [Xa, Xb, Ya, Yb] = diffieHellman(p, g, a, b)
% variables p and g are both publicly available numbers, p is always prime.
% g is a primitive root of p, both a and b are private values.
function pow = powerFunc(a, b, p)
if b == 1
pow = a;
end
pow = mod(power(a, b), p);
end
% Xa and Xb are the private keys for Alex and Bob respectively
Xa = powerFunc(g, a, p);
Xb = powerFunc(g, b, p);
% Ya and Yb are the final secret keys for Alex and Bob respectively
Ya = powerFunc(Xb, a, p);
Yb = powerFunc(Xa, b, p);
end
(You can add this code to MATLAB function block of Simulink directly.)
You can learn more about Diffie Hellman key exchange algorithm using the following link:
I hope this helps, thanks!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Naming Conventions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!