-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_phase1.py
More file actions
272 lines (214 loc) · 7.86 KB
/
client_phase1.py
File metadata and controls
272 lines (214 loc) · 7.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# -*- coding: utf-8 -*-
"""Client_phase1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1h2Z5FXCU4nZ9GIzc8RRecSxTiZOZjLjI
"""
!pip install ecpy
!pip install pycryptodome
# -*- coding: utf-8 -*-
import math
import timeit
import random
import sympy
import warnings
from random import randint, seed
import sys
from ecpy.curves import Curve,Point
from Crypto.Hash import SHA3_256
import requests
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
import random
import re
import json
API_URL = 'http://cryptlygos.pythonanywhere.com'
#CRYPTOGRAPHY CS411 FALL 2020 TERM RPOJECT PHASE 1
#DEVELOPING SOFTWARE FOR REGISTRATION & STATION TO STATION PROTOCOL
#IMPLEMENTED BY DENIZ CANGI, GULSEN GORKEM KOSE
stuID = 25359
#GET THE CURVE, ORDER, FIELD AND GENERATOR
curve = Curve.get_curve('secp256k1')
q = curve.order
p = curve.field
P = curve.generator
#LONGTERM PRIVATE AND PUBLIC KEYS, BELONG TO 25359
sL = 7607314394506061677990466796842274315842801300199560769842840753281729479854
lkey = Point(0x8642a0854b673af6989e0d4e109228543dabb4bf989beb4ff7d9324947405d9e , 0x17508f7382c066dc1e92f58a1a6268aa8f1a2a6ab88fd1ff151ccf30ba307824, curve)
#THIS PART IS FOR REGISTRATION
"""
#RANDOMLY SELECT LONG TERM SECRET KEY
sA = Random.new().read(int(math.log(q-1,2)))
sA = int.from_bytes(sA, byteorder='big') % q
print("sL =",sA)
#CREATE LONG TERM PUBLIC KEY WITH P AND LONG TERM SECRET KEY
lkey = sA*P
print("lkey =",lkey)
print("lkey.x =",lkey.x)
print("lkey.y =",lkey.y)
"""
#server's long term key
QSer_long = Point(0xc1bc6c9063b6985fe4b93be9b8f9d9149c353ae83c34a434ac91c85f61ddd1e9 , 0x931bd623cf52ee6009ed3f50f6b4f92c564431306d284be7e97af8e443e69a8c, curve)
#SIGNATURE GENERATION FOR STUID
def signStuID(stuID):
k = Random.new().read(int(math.log(q-2,2)))
k = int.from_bytes(k, byteorder='big')%q
R = k*P
r = R.x % q
hashVal = SHA3_256.new(bytes(str(stuID), 'utf-8')+ r.to_bytes((r.bit_length()+7)//8, byteorder = 'big'))
h = int.from_bytes(hashVal.digest(), 'big') % q
print("h for registration =", h)
s = (sA*h + k)%q
print("s for registration =",s)
return s,h
try:
#REGISTRATION
"""
mes = {'ID':stuID, 'h': h, 's': s, 'LKEY.X': lkey.x, 'LKEY.Y': lkey.y}
response = requests.put('{}/{}'.format(API_URL, "RegStep1"), json = mes)
if((response.ok) == False): raise Exception(response.json())
print(response.json())
print("Enter verification code which is sent to you: ")
code = int(input())
mes = {'ID':stuID, 'CODE': code}
response = requests.put('{}/{}'.format(API_URL, "RegStep3"), json = mes)
if((response.ok) == False): raise Exception(response.json())
print(response.json())"""
#STS PROTOCOL
#CREATE EPHEMERAL KEYS:
sA = Random.new().read(int(math.log(q-1,2)))
sA = int.from_bytes(sA, byteorder='big') % q
print("sA =",sA)
ekey = sA*P
print("ekey.x =", ekey.x,"ekey.y =", ekey.y)
#SEND THE PUBLIC KEY TO THE SERVER
mes = {'ID': stuID, 'EKEY.X': ekey.x, 'EKEY.Y': ekey.y}
response = requests.put('{}/{}'.format(API_URL, "STSStep1&2"), json = mes)
if((response.ok) == False): raise Exception(response.json())
res=response.json()
#calculate T,K,U
print()
#RESPONSE OF THE SERVER, WHICH INCLUDES THE EPHEMERAL KEY OF SERVER
print("res =",res)
QB_x = res.get('SKEY.X')
QB_y = res.get('SKEY.Y')
#CREATE THE EPHEMERAL KEY OF THE SERVER
QB = Point(QB_x, QB_y, curve)
T= sA*QB
print("T =",T)
Tx = T.x
Ty = T.y
temp = "BeYourselfNoMatterWhatTheySay"
U=str(Tx)+str(Ty)+temp
print("U =", U)
U_bytes= bytes(U, 'utf-8')
hashvalue = SHA3_256.new(U_bytes)
K = hashvalue.digest()
print("K =",K)
#Sign Message
#SIGNATURE GENERATION FUNCTION THAT TAKES THE MESSAGE AND RETURN THE SIGNATURE TUPLE
def SignSL(message):
k = Random.new().read(int(math.log(q-2,2)))
k = int.from_bytes(k, byteorder='big')%q
R = k*P
r = R.x % q
mr = bytes(message, 'utf-8')+ r.to_bytes((r.bit_length()+7)//8, byteorder = 'big')
hashVal = SHA3_256.new(mr)
h = int.from_bytes(hashVal.digest(), 'big') % q
s = (sL*h + k)%q
return s,h
W1 = str(ekey.x)+str(ekey.y)+str(QB.x)+str(QB.y)
print()
print("W1 =",W1)
SigA_s, SigA_h = SignSL(W1)
print("(s,h) =",SigA_s, SigA_h)
plaintext = bytes("s" + str(SigA_s)+ "h" + str(SigA_h), 'utf-8')
print("plaintext =", plaintext)
# Encyption
#ENCRYPTION FUNCTION THAT TAKES THE KEY AND PLAINTEXT AS BYTES AND RETURNS THE CIPHERTEXT AS INTEGER
def Encryption(key,plaintext):
cipher = AES.new(key, AES.MODE_CTR)
ctext = cipher.nonce + cipher.encrypt(plaintext)
ctext = int.from_bytes(ctext, byteorder='big')
return ctext
ctext = Encryption(K, plaintext)
print("int of Y1 =", ctext)
###Send encrypted-signed keys and retrive server's signed keys
mes = {'ID': stuID, 'FINAL MESSAGE': ctext}
response = requests.put('{}/{}'.format(API_URL, "STSStep4&5"), json = mes)
if((response.ok) == False): raise Exception(response.json())
ctext= response.json()
#Decrypt
#DECRYPTION FUNCTION THAT TAKES THE CIPHERTEXT AS INTEGER, KEY AND THE LENGTH OF NONCE
#RETURNS THE DECRYPTED CIPHERTEXT AS STRING
def Decryption(ctext,key,nonce_len):
ctext = ctext.to_bytes((ctext.bit_length()+7)//8, byteorder = 'big')
cipher = AES.new(key, AES.MODE_CTR, nonce=ctext[0:nonce_len])
dtext = cipher.decrypt(ctext[nonce_len:])
decrypt_text = dtext.decode('utf-8')
return decrypt_text
print()
print("int of Y2 =", ctext)
decrypt_text = Decryption(ctext,K,8)
print("Decrypted text: ", decrypt_text)
#verify
#SIGNATURE VERIFICATION FUNCTION THAT TAKES MESSAGE AND VERIFY THE SIGNATURE
#IT USES THE LONG TERM KEY OF THE SERVER Qser_long
#IT RETURNS TRUE IF h' = h AND RETURNS FALSE IF h' != h
def SigVer(message):
word_h = decrypt_text.find("h")
s = int(decrypt_text[1:word_h])
h = int(decrypt_text[word_h+1:])
sig_ = (s,h)
print("(s,h) =", sig_)
V = s*P - h * QSer_long
print("V =", V)
Vx = V.x % q
print("Vx =", Vx)
mv = bytes(message, 'utf-8')+ Vx.to_bytes((Vx.bit_length()+7)//8, byteorder = 'big')
hashVal_ = SHA3_256.new(mv)
h_ = int.from_bytes(hashVal_.digest(), 'big') % q
print("h'=", h_)
if h_ == h:
return True
else:
return False
W2 = str(QB.x)+str(QB.y)+str(ekey.x)+str(ekey.y)
print("W2 =", W2)
verified = SigVer(W2)
if verified:
print("Signature verified!")
else:
print("Signature not verified!")
#get a message from server for
mes = {'ID': stuID}
response = requests.get('{}/{}'.format(API_URL, "STSStep6"), json=mes)
ctext= response.json()
#Decrypt
print()
print("ciphertext received from server =", ctext)
decrypt_text = Decryption(ctext, K, 8)
print("Message from server: ", decrypt_text)
#Add 1 to random to create the new message and encrypt it
random_number_index = decrypt_text.find(". ")
random_number_str = decrypt_text[random_number_index+2:]
random_number = int(random_number_str)
print("RAND =", random_number)
print("MESSAGE =", decrypt_text[0:decrypt_text.find(random_number_str)])
print()
W4 = decrypt_text[0:decrypt_text.find(random_number_str)] + str(random_number + 1)
print("W4 =", random_number+1)
print("MessageToServer =", W4)
W4_bytes = bytes(W4, 'utf-8')
ct = Encryption(K,W4_bytes)
#send the message and get response of the server
mes = {'ID': stuID, 'ctext': ct}
response = requests.put('{}/{}'.format(API_URL, "STSStep7&8"), json = mes)
ctext= response.json()
decrypt_text = Decryption(ctext, K, 8)
print()
print("Message from server:", decrypt_text)
except Exception as e:
print(e)