Last active
September 1, 2015 22:17
-
-
Save eu90h/9dd9c2a1051dedfd137e to your computer and use it in GitHub Desktop.
Diffie-Hellman key exchange in Racket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
; groups.rkt is located in the repository https://github.com/eu90h/elgamal-signature | |
(require math "groups.rkt") | |
(define (diffie-hellman in out [p ike-2048] [g 2]) | |
; Alice uniformly chooses a random integer a s.t. 1 <= a < p - 1 | |
; and then computes A := g^a mod p | |
(let* ([a (random-integer 1 (- p 1))] | |
[A (modular-expt g a p)]) | |
; Alice then sends A to her interlocutor Bob. | |
(displayln (number->string A 16) out) | |
; Meanwhile, Bob is repeating the same process as Alice, and sends Alice a value B := g^b mod p, | |
; where the positive integer b is chosen analogously to Alice's a. | |
(let ([B (string->number (read-line in) 16)]) | |
; now Alice computes k_a := B^a mod p, while Bob computes k_b := A^b mod p. | |
; it works out that k_a = k_b, hence Alice and Bob have created a shared key. | |
(modular-expt B a p)))) | |
(module+ test | |
(require rackunit) | |
(define p ike-2048) | |
(define g 2) | |
(define b (random-integer 1 (- p 1))) | |
(define B (modular-expt g b p)) | |
(define (create-bob-port) | |
(open-input-string (number->string B 16))) | |
(define out (open-output-string)) | |
(define k_a (diffie-hellman (create-bob-port) out)) | |
(define k_b (modular-expt (string->number (string-trim (get-output-string out) | |
(string #\newline)) 16) b p)) | |
(check-equal? k_a k_b)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment