Last active
June 19, 2021 09:38
-
-
Save skipcloud/04e5af0a4899b182f131ee49d81f56bf to your computer and use it in GitHub Desktop.
diffie-hellman key exchange
This file contains 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
BASE = 11 | |
MODULUS = 81 | |
class Person | |
def secret_num | |
@num ||= rand(50).to_i | |
end | |
def prime_to_the_power_of_secret_num | |
BASE ** secret_num | |
end | |
def presecret | |
prime_to_the_power_of_secret_num % MODULUS | |
end | |
def master_secret(other_half) | |
(other_half ** secret_num) % MODULUS | |
end | |
end | |
def red(text) | |
"\e[31m#{text}\e[0m" | |
end | |
def blue(text) | |
"\e[36m#{text}\e[0m" | |
end | |
alice = Person.new | |
bob = Person.new | |
puts <<EOF | |
Alice and Bob, in public, agree on a prime number and a modulus. The prime number | |
needs to be a primative root prime modulus of the modulus number. | |
They choose the following: | |
prime number: #{blue(BASE)} | |
modulus: #{blue(MODULUS)} | |
These numbers are blue to indicate that they are publically known as they are | |
sent across the wire in plain text. Secret numbers will be coloured red. | |
Alice then chooses a number which she keeps secret. In this case she chooses #{red(alice.secret_num)}. | |
She then raises the prime number chosen earlier to the power of | |
her secret number: #{blue(BASE)}^#{red(alice.secret_num)} = #{alice.prime_to_the_power_of_secret_num} | |
Then she uses the modulus on that result to get her presecret: #{alice.prime_to_the_power_of_secret_num} mod #{blue(MODULUS)} = #{blue(alice.presecret)} | |
At the same time as Alice Bob is following the exact same steps. | |
Bob's values: | |
his secret: #{red(bob.secret_num)} | |
prime raised to his secret: #{bob.prime_to_the_power_of_secret_num} | |
modulus result: #{blue(bob.presecret)} | |
The modulus results (presecrets) are exchanged over plaintext, they will then raise the | |
number they receive to the power of their own secret number and use the modulus on the result. | |
Let's walk through it. | |
Alice takes Bob's presecret and raises it to her secret number then mods it: | |
(#{blue(bob.presecret)} ^ #{red(alice.secret_num)}) mod #{blue(MODULUS)} = #{red(alice.master_secret(bob.presecret))} | |
Bob takes Alice's modulus and raises it to his secret number then mods it: | |
(#{blue(alice.presecret)} ^ #{red(bob.secret_num)}) mod #{blue(MODULUS)} = #{red(bob.master_secret(alice.presecret))} | |
The symmetric key is #{red(alice.master_secret(bob.presecret))} which both parties can use to encrypt messages. | |
EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment