Skip to content

Instantly share code, notes, and snippets.

@strawstack
Last active December 15, 2019 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strawstack/fce1cd0e9cc372f992b284da57981535 to your computer and use it in GitHub Desktop.
Save strawstack/fce1cd0e9cc372f992b284da57981535 to your computer and use it in GitHub Desktop.
# N = RandomPrime[{2^1020, 2^1025}]
# G = PrimitiveRoot[N]
import random
N = 450399019389671650452249084921759078761980896382890703798228170622215717666353
G = 3
def msgToNumber(msg):
total = 0
for i in range(len(msg)):
c = msg[i]
offset = 8 * (len(msg) - i - 1)
total += (ord(c) << offset)
return total
def numberToMsg(number):
msg = []
while number > 0:
c_num = number & 0b11111111
number = number >> 8
msg.append(chr(c_num))
return "".join(list(reversed(msg)))
# Alice and Bob choose private numbers
x = random.randrange(2**16, 2**18)
y = random.randrange(2**16, 2**18)
print("x:", x)
print("y:", y)
# Alice and Bob calculate exchange values
R1 = (G**x) % N
R2 = (G**y) % N
print("R1:", R1)
print("R2:", R2)
# R1 and R2 are exchanged and used to calculate
# K1, K2 where K1 == K2
K1 = (R2**x) % N
K2 = (R1**y) % N
print("K1:", K1)
# Plain text Message
msg = "Your secret message!"
print("msg:", msg)
# Message encrypted and sent by Alice
c = msgToNumber(msg) ^ K1
print("c:", c)
# Bob decrypts message and reads it
d = numberToMsg(c ^ K2)
print("d:", d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment