Diffie-Hellman Key Exchange

Implementation and Analysis in Java

CS285: Discrete Mathematics Section 963

Instructor: Dr.

College of Computer and Information Sciences (CCIS)

SHOUG FAWAZ ABDULLAH ALOMRAN
ALJOHARAH WALEED A ALBAWARDI
YARA MUTLAQ MOHAMMED ALZAMEL
FAI MOHAMMAD BIN KHANJAR

تبادل مفاتيح ديفي–هيلمان

التنفيذ والتحليل بلغة جافا

CS285: الرياضيات المتقطعة الشعبة 963

المحاضر: د.

كلية علوم الحاسب والمعلومات (CCIS)

SHOUG FAWAZ ABDULLAH ALOMRAN
ALJOHARAH WALEED A ALBAWARDI
YARA MUTLAQ MOHAMMED ALZAMEL
FAI MOHAMMAD BIN KHANJAR

Table of Contents

Jump to any section of the report:

جدول المحتويات

انتقل إلى أي قسم في التقرير:

1. Introduction

In today's digital world, secure communication is the need of the hour to protect sensitive information being exchanged over public networks. The Diffie-Hellman key exchange algorithm allows two parties to agree on a shared secret key without actually exchanging it, and forms a basis for many of today's encryption schemes.

The following Java code for the Diffie–Hellman implementation is provided for CS285, Discrete Mathematics for Computing. The developed system incorporates fundamental mathematical concepts regarding modular arithmetic and exponentiation. The system simulates secure key generation and exchange between two entities using the Diffie–Hellman key exchange method. A simple encryption and decryption mechanism has also been provided to illustrate how the derived shared key can be used to secure messages.

We divide the program into the following classes: Parameters handles all public values, KeyExchange generates and computes keys, Encryptor encrypts messages, and Validator, Helpers, and Utils ensure correct input handling and output formatting. The Main class integrates all components of the system and allows users to test both a predefined numerical example and a live interactive mode.

The project ties together theoretical mathematics and programming in practice, showing how secure key exchange and encryption work in real-world systems.

1. المقدمة

في عالمنا الرقمي اليوم أصبحت الاتصالات الآمنة ضرورة لحماية المعلومات الحساسة التي يتم تبادلها عبر الشبكات العامة. تتيح خوارزمية تبادل المفاتيح ديفي–هيلمان لطرفين الاتفاق على مفتاح سري مشترك دون تبادله بشكل مباشر، وهي أساس لكثير من أنظمة التشفير الحديثة.

تقدم شيفرة جافا التالية كتطبيق لطريقة ديفي–هيلمان ضمن مقرر CS285 (الرياضيات المتقطعة للحوسبة). يعتمد النظام على مفاهيم رياضية أساسية مثل الحساب المعياري والأسس. يحاكي النظام توليد المفاتيح وتبادلها بشكل آمن بين كيانين باستخدام ديفي–هيلمان، كما يتضمن آلية بسيطة للتشفير وفك التشفير لتوضيح كيفية استخدام المفتاح المشترك لحماية الرسائل.

تم تقسيم البرنامج إلى عدة أصناف: يتولى Parameters القيم العامة، ويقوم KeyExchange بتوليد وحساب المفاتيح، ويقوم Encryptor بتشفير الرسائل، بينما تضمن Validator و Helpers و Utils صحة المدخلات وتنسيق المخرجات. يقوم الصنف Main بدمج جميع المكونات ويوفر وضع المثال العددي ووضعا تفاعليا مباشرا.

يربط هذا المشروع بين النظرية الرياضية والتطبيق البرمجي لإظهار كيفية عمل تبادل المفاتيح والتشفير في الأنظمة الواقعية.

1.1 Purpose of the Diffie–Hellman Key Exchange and Its Applications

The Diffie-Hellman key exchange is a cryptography technique whose main purpose is to allow two parties to exchange a key that can be used for encrypting messages. This shared key can be used in public channels that ensures no one unauthorized can read it. The key concept was developed by Ralph Merkle but was published by Whitfield Diffie and Martin Hellman in 1976, which is why it's named after them.

Real-World Applications

  • TLS: DH variants during the handshake generate session keys that protect web traffic.
  • SSH: Establishes a secret key early in the connection to secure commands and file transfers.
  • Royal Convoy Security: Vehicles and control centers coordinate securely using a DH-family exchange.

1.1 الهدف من تبادل مفاتيح ديفي–هيلمان وتطبيقاته

يعد تبادل مفاتيح ديفي–هيلمان أسلوبا في علم التشفير يهدف إلى تمكين طرفين من إنشاء مفتاح مشترك يمكن استخدامه لتشفير الرسائل. يتم إنشاء المفتاح عبر قناة عامة بحيث لا يستطيع غير المصرح لهم استخلاصه. طورت الفكرة الأساسية بواسطة رالف ميركل، ثم نشرت رسميا بواسطة ويتفيلد ديفي ومارتن هيلمان عام 1976، ومن هنا جاءت التسمية.

تطبيقات واقعية

  • TLS: تستخدم أشكال DH أثناء المصافحة لإنشاء مفاتيح جلسة تحمي حركة الويب.
  • SSH: ينشئ مفتاحا سريا في بداية الاتصال لتأمين الأوامر ونقل الملفات.
  • أمن المواكب: يمكن للمركبات ومراكز التحكم التنسيق بشكل آمن باستخدام تبادل من عائلة DH.

1.2 Algorithm Explanation

The Diffie–Hellman key exchange algorithm allows two parties to create a common secret over insecure channels by performing modular exponentiation on agreed public parameters.

How It Works

  1. Agree on prime q and generator (primitive root) α.
  2. Choose private keys Xa and Xb with 1 ≤ X < q−1.
  3. Compute public keys: Ya = αXa mod q, Yb = αXb mod q.
  4. Exchange Ya and Yb.
  5. Compute shared secret: k = YbXa mod q = YaXb mod q.

Even though q, α, Ya, and Yb are public, inferring Xa or Xb is computationally infeasible for large, well-chosen parameters due to the Discrete Logarithm Problem.

1.2 شرح الخوارزمية

تمكن خوارزمية ديفي–هيلمان طرفين من إنشاء سر مشترك عبر قناة غير آمنة من خلال إجراء عمليات الأسس المعيارية على معلمات عامة يتم الاتفاق عليها مسبقا.

كيف تعمل

  1. الاتفاق على عدد أولي q ومولد (جذر بدائي) α.
  2. اختيار مفاتيح خاصة Xa و Xb بحيث 1 ≤ X < q−1.
  3. حساب المفاتيح العامة: Ya = αXa mod q و Yb = αXb mod q.
  4. تبادل Ya و Yb.
  5. حساب السر المشترك: k = YbXa mod q = YaXb mod q.

رغم أن q و α و Ya و Yb قيم عامة، فإن استنتاج Xa أو Xb غير عملي حسابيا عند استخدام معلمات كبيرة ومختارة بشكل صحيح بسبب صعوبة مسألة اللوغاريتم المتقطع.

1.3 Numerical Example

Two cars and a control center must communicate securely during a royal convoy.

Step-by-Step Calculation

  1. Public parameters: q = 23, α = 5.
  2. Car 1 chooses Xa = 6Ya = 56 mod 23 = 8.
  3. Car 2 chooses Xb = 15Yb = 515 mod 23 = 19.
  4. Exchange Ya and Yb.
  5. Shared secret: Car 1 → 196 mod 23 = 2; Car 2 → 815 mod 23 = 2.
  6. Both derive the same key: 2.
Numerical Example Screenshot

Numerical example with fixed values (q=23, α=5).

1.3 مثال عددي

تحتاج سيارتان ومركز تحكم إلى التواصل بشكل آمن أثناء موكب رسمي.

الحساب خطوة بخطوة

  1. المعلمات العامة: q = 23 و α = 5.
  2. تختار السيارة 1 Xa = 6Ya = 56 mod 23 = 8.
  3. تختار السيارة 2 Xb = 15Yb = 515 mod 23 = 19.
  4. يتم تبادل Ya و Yb.
  5. السر المشترك: السيارة 1 → 196 mod 23 = 2 وال سيارة 2 → 815 mod 23 = 2.
  6. يتوصل الطرفان إلى نفس المفتاح: 2.
Numerical Example Screenshot

مثال عددي بقيم ثابتة (q=23 و α=5).

1.4 Advantages and Limitations of Diffie–Hellman

Strengths of Diffie–Hellman

  • No pre-shared secret: Two parties can securely derive a shared key over a public channel.
  • Forward secrecy (with ephemeral keys): New private keys per session protect past communications.
  • Mathematical soundness: Security rests on the Discrete Logarithm Problem (DLP).
  • Widely implemented: A proven cornerstone of secure protocols for decades.

Limitations of Diffie–Hellman

  • No authentication by default: Vulnerable to MitM unless combined with certificates or signatures.
  • Weak parameter selection: Small or reused primes can enable precomputation attacks.
  • Performance overhead: Large modular exponentiations are heavy vs symmetric crypto.

While Diffie–Hellman provides a strong mathematical basis for key exchange, its security depends on careful parameter management and the inclusion of authentication to avoid interception or impersonation.

1.4 المزايا والقيود في ديفي–هيلمان

نقاط القوة

  • لا يحتاج سرا مسبقا: يمكن لطرفين اشتقاق مفتاح مشترك عبر قناة عامة.
  • سرية أمامية (مع مفاتيح مؤقتة): مفاتيح جديدة لكل جلسة تحمي الاتصالات السابقة.
  • متانة رياضية: الأمان قائم على صعوبة مسألة اللوغاريتم المتقطع.
  • شائع الاستخدام: حجر أساس في بروتوكولات الأمان منذ عقود.

القيود

  • بدون توثيق افتراضي: قابل لهجوم الرجل في الوسط ما لم يدمج مع شهادات أو توقيعات.
  • اختيار معلمات ضعيف: استخدام أعداد أولية صغيرة أو معاد استخدامها قد يسهل هجمات الاستباق الحسابي.
  • عبء أداء: عمليات الأسس المعيارية الكبيرة أبطأ مقارنة بالتشفير المتماثل.

رغم أن ديفي–هيلمان يقدم أساسا رياضيا قويا لتبادل المفاتيح، إلا أن الأمان يعتمد على إدارة المعلمات بعناية وإضافة طبقة توثيق لتجنب الاعتراض أو الانتحال.

1.5 Comparison Between Diffie–Hellman (DH) and Elliptic Curve Diffie–Hellman (ECDH)

Elliptic Curve Diffie–Hellman (ECDH) follows the same principle as DH but replaces modular arithmetic with elliptic-curve mathematics, providing stronger security with smaller key sizes.

Shared Principles

  • Both allow two parties to establish a shared secret without prior key exchange.
  • Security relies on computational hardness problems: DLP (DH) and ECDLP (ECDH).
  • Neither provides authentication by itself; must be combined with signatures or certificates.
  • Both can achieve forward secrecy using ephemeral key pairs.

Key Differences

  • Security per bit: ECDH achieves equivalent security with smaller key sizes.
  • Performance: ECDH is typically faster and lighter on constrained devices.
  • Parameter handling: DH uses primes and generators; ECDH uses standardized curves.
  • Resistance to precomputation: Curves reduce feasibility of mass precomputation attacks.
  • Deployment: ECDH dominates modern protocols (e.g., TLS 1.3).
DH vs ECDH Venn Diagram

Overlap between DH and ECDH.

1.5 مقارنة ديفي–هيلمان (DH) مع ديفي–هيلمان بالمنحنيات الإهليلجية (ECDH)

يتبع ECDH نفس مبدأ DH لكنه يستبدل الحساب المعياري برياضيات المنحنيات الإهليلجية، مما يوفر أمانا أعلى بمفاتيح أصغر.

مبادئ مشتركة

  • كلاهما يمكن طرفين من إنشاء سر مشترك دون تبادل مفتاح مسبقا.
  • يعتمد الأمان على مسائل صعبة حسابيا: DLP في DH و ECDLP في ECDH.
  • لا يوفر أي منهما توثيقا بذاته؛ يجب دمجه مع توقيعات أو شهادات.
  • يمكن تحقيق السرية الأمامية باستخدام مفاتيح مؤقتة.

أهم الفروقات

  • الأمان لكل بت: يحقق ECDH أمانا مكافئا بمفاتيح أصغر.
  • الأداء: غالبا ما يكون ECDH أسرع وأخف على الأجهزة محدودة الموارد.
  • إدارة المعلمات: يعتمد DH على اختيار q و α، بينما يستخدم ECDH منحنيات معيارية.
  • مقاومة الاستباق الحسابي: تقل قابلية هجمات الاستباق واسعة النطاق مع المنحنيات.
  • الانتشار: يهيمن ECDH على البروتوكولات الحديثة (مثل TLS 1.3).
DH vs ECDH Venn Diagram

منطقة التقاطع بين DH و ECDH.

2. Code Description

2.1 How the Program Works

The program is organized into classes: Main (driver), Parameters (public values q and α), KeyExchange (private/public keys and shared secret), Encryptor (demo XOR encryption keyed by SHA-256(shared secret)), Validator (prime/range/message validations), Utils (helpers), and Helpers (interactive prompts).

2. وصف الشيفرة

2.1 كيف يعمل البرنامج

يتكون البرنامج من عدة أصناف: Main (المشغل)، Parameters (القيم العامة q و α)، KeyExchange (المفاتيح الخاصة والعامة والسر المشترك)، Encryptor (تشفير XOR توضيحي مع مفتاح مشتق من SHA-256 للسر المشترك)، Validator (التحقق من القيم)، Utils (مساعدات عامة)، و Helpers (مطالبات تفاعلية).

2.2 Implementation of Each Part

Key Generation

Key Generation Implementation
private void generateKeys() { this.privateKey = new BigInteger(getQ().bitLength(), random) .mod(getQ().subtract(BigInteger.TWO)) .add(BigInteger.ONE); // 1 <= x <=q-2 this.publicKey=getAlpha().modPow(privateKey, getQ()); // Y=α^x mod q }

The private key is uniform in [1, q−2]. The public key is computed as Y = α^x mod q.

Encryption

Encryption Implementation
String encrypt(String msg, BigInteger sharedKey) throws Exception { byte[] msgByte = msg.getBytes(StandardCharsets.UTF_8); byte[] keyByte = Key(sharedKey); // SHA-256 hash of shared key byte[] cipherMsgByte = xor(msgByte, keyByte); // demo XOR cipher return Base64.getEncoder().encodeToString(cipherMsgByte); }

For demonstration, we hash the shared secret to a fixed-length byte key and XOR the plaintext bytes, then Base64-encode.

Decryption

Decryption Implementation
String decrypt(String base64cipherMsg, BigInteger sharedKey) throws Exception { byte[] keyByte = Key(sharedKey); byte[] cipherMsgByte = Base64.getDecoder().decode(base64cipherMsg); byte[] msgByte = xor(cipherMsgByte, keyByte); return new String(msgByte, StandardCharsets.UTF_8); }

Using the same hash and XOR reverses the demo cipher and recovers the message.

2.2 تفاصيل التنفيذ

توليد المفاتيح

Key Generation Implementation
private void generateKeys() { this.privateKey = new BigInteger(getQ().bitLength(), random) .mod(getQ().subtract(BigInteger.TWO)) .add(BigInteger.ONE); // 1 <= x <=q-2 this.publicKey=getAlpha().modPow(privateKey, getQ()); // Y=α^x mod q }

يتم اختيار المفتاح الخاص بشكل منتظم ضمن المجال [1, q−2]، ثم يحسب المفتاح العام وفق Y = α^x mod q.

التشفير

Encryption Implementation
String encrypt(String msg, BigInteger sharedKey) throws Exception { byte[] msgByte = msg.getBytes(StandardCharsets.UTF_8); byte[] keyByte = Key(sharedKey); // SHA-256 hash of shared key byte[] cipherMsgByte = xor(msgByte, keyByte); // demo XOR cipher return Base64.getEncoder().encodeToString(cipherMsgByte); }

لأغراض التوضيح، يتم تجزئة السر المشترك لإنتاج مفتاح بطول ثابت ثم إجراء XOR على بايتات النص، وبعدها ترميز الناتج بصيغة Base64.

فك التشفير

Decryption Implementation
String decrypt(String base64cipherMsg, BigInteger sharedKey) throws Exception { byte[] keyByte = Key(sharedKey); byte[] cipherMsgByte = Base64.getDecoder().decode(base64cipherMsg); byte[] msgByte = xor(cipherMsgByte, keyByte); return new String(msgByte, StandardCharsets.UTF_8); }

استخدام نفس التجزئة وعملية XOR يعكس التشفير ويسترجع الرسالة الأصلية.

2.3 Challenges Faced and How We Overcame Them

Input Validation

Non-prime q, invalid α ranges, or short messages previously crashed the program; robust prompting loops now enforce constraints and re-ask on error.

Class Integration

Standardized method names and types across modules to simplify the Main driver and reduce coupling issues.

Modular Arithmetic Accuracy

Adopted Java’s modPow to avoid overflow and correctness issues for public/shared key derivations.

Byte Handling Consistency

Enforced UTF-8 and Base64 to keep encryption/decryption round-trips stable across platforms.

2.3 التحديات وكيف تم تجاوزها

التحقق من المدخلات

كانت القيم غير الأولية لـ q أو قيم α خارج النطاق أو الرسائل القصيرة تسبب أعطالا؛ تمت إضافة حلقات إدخال تتحقق من الشروط وتعيد الطلب عند الخطأ.

تكامل الأصناف

تم توحيد أسماء الدوال وأنواع البيانات بين المكونات لتبسيط الصنف Main وتقليل التشابك.

دقة الحسابات المعيارية

تم الاعتماد على modPow في جافا لتجنب مشاكل الفيض وضمان صحة اشتقاق المفاتيح.

ثبات معالجة البايتات

تم اعتماد UTF-8 و Base64 لضمان ثبات عملية التشفير وفك التشفير عبر المنصات.

3. Results and Test Cases

Live Mode – Manual

Live Mode Manual

Manual input of q, α, and message – valid parameters and correct key exchange.

In manual live mode, users provide q, α, and the message. The program validates inputs, computes public keys, derives the shared key, encrypts, and then decrypts the message. Successful decryption confirms both parties derived the same shared key.

Observation

This confirms that the program correctly implements the mathematical logic of the Diffie–Hellman key exchange algorithm.


Live Mode – Alpha Error

Alpha Error

Invalid α range, the system rejects and re-prompts until valid.

This test demonstrates input validation. If α is outside (1 < α < q), the program rejects it and re-prompts, preventing invalid configurations.

Validation Mechanism

The Validator and Helpers classes enforce constraints for q and α before continuing.


Numerical Example (Fixed)

Numerical Example Fixed

Fixed small integer example – both users derive identical shared key (K).

This example uses small integer values to visually demonstrate how two users derive the same shared secret key.

3. النتائج وحالات الاختبار

الوضع المباشر – يدوي

Live Mode Manual

إدخال يدوي لـ q و α والرسالة – معلمات صحيحة وتبادل مفاتيح سليم.

في الوضع المباشر اليدوي، يقوم المستخدم بإدخال q و α والرسالة. يتحقق النظام من صحة المدخلات، ثم يحسب المفاتيح العامة ويشتق المفتاح المشترك ويجري التشفير وفك التشفير. نجاح فك التشفير يثبت أن الطرفين حصلا على نفس المفتاح.

ملاحظة

يؤكد ذلك أن البرنامج يطبق المنطق الرياضي لتبادل مفاتيح ديفي–هيلمان بشكل صحيح.


الوضع المباشر – خطأ في α

Alpha Error

قيمة α غير صحيحة، يتم رفضها وإعادة الطلب حتى تصبح ضمن النطاق.

توضح هذه الحالة التحقق من المدخلات. إذا كانت α خارج (1 < α < q) يتم رفضها وإعادة الطلب لتجنب إعدادات غير صحيحة.

آلية التحقق

تعمل Validator و Helpers على فرض الشروط الخاصة بـ q و α قبل المتابعة.


مثال عددي (ثابت)

Numerical Example Fixed

مثال بأعداد صغيرة – يحصل الطرفان على نفس المفتاح المشترك (K).

يستخدم هذا المثال أعدادا صغيرة لتوضيح كيفية اشتقاق نفس السر المشترك بصريا.

4. Team Contribution

All members collaborated on the Java implementation and the report. Roles below summarize primary ownership while acknowledging shared reviews and integration work.

Yara Alzamel

Established program scaffolding for public parameters and helper routines, including generation of q and α and formatted output utilities.

Fai Bin Khanjar

Implemented DH mathematics (private/public/shared keys) and authored the guided numerical example; validated modular arithmetic correctness.

Aljoharah Albawardi

Built the encryption/decryption demo atop the shared secret and executed test runs; documented security considerations.

Shoug Alomran

Integrated modules into the driver, implemented validations and resilient input loops, coordinated final testing, and unified the report tone and structure.

4. مساهمة الفريق

ساهم جميع الأعضاء في تنفيذ المشروع بلغة جافا وإعداد التقرير. توضح النقاط التالية المسؤوليات الأساسية مع الإشارة إلى العمل الجماعي في المراجعة والدمج.

Yara Alzamel

إنشاء هيكل البرنامج للقيم العامة والدوال المساعدة بما يشمل توليد q و α وتنسيق المخرجات.

Fai Bin Khanjar

تنفيذ رياضيات DH (المفاتيح الخاصة والعامة والمشتركة) وكتابة المثال العددي والتحقق من صحة الحسابات.

Aljoharah Albawardi

بناء تجربة التشفير وفك التشفير بالاعتماد على المفتاح المشترك وتنفيذ حالات الاختبار وتوثيق اعتبارات الأمان.

Shoug Alomran

دمج المكونات في المشغل وتطبيق التحقق من المدخلات وتنظيم الاختبارات النهائية وتوحيد أسلوب التقرير وبنيته.

5. Conclusion

The project demonstrates how two parties can establish a shared secret over an insecure network using modular exponentiation and carefully validated parameters. It also highlights the importance of authentication wrappers and ephemeral keys to achieve practical security goals.

Future Growth Opportunities

Extend with authenticated key exchange, replace the demo XOR with AES-GCM using a KDF, and add ECDH support with standardized curves.

5. الخاتمة

يوضح المشروع كيفية تمكين طرفين من إنشاء سر مشترك عبر شبكة غير آمنة باستخدام الأسس المعيارية ومعلمات تم التحقق منها بعناية. كما يبرز أهمية إضافة التوثيق والمفاتيح المؤقتة لتحقيق أهداف أمان عملية.

فرص التطوير مستقبلا

إضافة تبادل مفاتيح موثق، واستبدال XOR التوضيحي بـ AES-GCM باستخدام KDF، وإضافة دعم ECDH عبر منحنيات معيارية.

6. References and Resources

Ambatipudi, S. (2024, June 6). Cryptographic advancements enabled by Diffie–Hellman. ISACA Journal, Volume 3.
Boneh, D., & Shparlinski, I. E. (2001). On the unpredictability of bits of the Elliptic Curve Diffie–Hellman scheme. CRYPTO 2001. Springer.
Diffie, W., & Hellman, M. E. (1976). New directions in cryptography. IEEE Transactions on Information Theory, 22(6), 644–654.
Haakegaard, R., & Lang, J. (2015). The Elliptic Curve Diffie–Hellman (ECDH). UCSB.
Krawczyk, H. (2005). HMQV: A High-Performance Secure Diffie-Hellman Protocol. Springer.

6. المراجع والموارد

Ambatipudi, S. (2024, June 6). Cryptographic advancements enabled by Diffie–Hellman. ISACA Journal, Volume 3.
Boneh, D., & Shparlinski, I. E. (2001). On the unpredictability of bits of the Elliptic Curve Diffie–Hellman scheme. CRYPTO 2001. Springer.
Diffie, W., & Hellman, M. E. (1976). New directions in cryptography. IEEE Transactions on Information Theory, 22(6), 644–654.
Haakegaard, R., & Lang, J. (2015). The Elliptic Curve Diffie–Hellman (ECDH). UCSB.
Krawczyk, H. (2005). HMQV: A High-Performance Secure Diffie-Hellman Protocol. Springer.

Appendix – Full Source Code

Main Class
/* Keep your full code here exactly as-is. Code blocks are identical in both languages. */

الملحق – الشيفرة المصدرية الكاملة

Main Class
/* ضع الشيفرة كاملة هنا كما هي. الشيفرة لا تحتاج ترجمة. */