def t2(): kalice = binascii.unhexlify("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a") kalice = decode_scalar_25519(kalice) kbob = binascii.unhexlify("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb") kbob = decode_scalar_25519(kbob) u = 9 G = Point(u,None,cv) kaliceG = kalice*G print("ALICE") print(" k : %.064x"%kalice) print(" u : %.064x"%u) print(" ku: %.064x"%kaliceG.x) kbobG = kbob*G print("BOB") print(" k : %.064x"%kbob) print(" u : %.064x"%u) print(" ku: %.064x"%kbobG.x) shared1 = kbob*kaliceG print("SHARED1") print(" X: %.064x"%shared1.x) shared2 = kalice*kbobG print("SHARED2") print(" X: %.064x"%shared2.x)
def session_key_generation(sA_i, qBj_x, qBj_y): ''' print("qbjx type: ", type(qBj_x)) if(type(qBj_x) is int): qBj_x = hex(qBj_x) qBj_y = hex(qBj_y) print(qBj_x) print("qbjx type: ", type(qBj_x)) ''' qB_j = Point(qBj_x, qBj_y, curve) T = sA_i * qB_j U = str(T.x) + str(T.y) + "NoNeedToRunAndHide" U = bytes(U, 'utf-8') # Compute the session keys k_enc = SHA3_256.new(U) k_enc = k_enc.digest() k_mac = SHA3_256.new(k_enc) k_mac = k_mac.digest() return k_enc, k_mac
def sendEphemeralKeys(): # long term keys s_l, Q_l = 13085853449963706822679688925724357385610122371856980557637515554534105534392, Point( 99706965781601861644488801678706331501908275461350155965248416002017363728845, 34959479883630730429995407912028272742489857511375877620317188275102881036203, E) # generate ephemeral keys ephemeralKeys = [] for i in range(10): ephemeralKeys.append(keyGeneration(n, P)) # send ephemeral key i = 0 for keyPair in ephemeralKeys: ekey = Point(keyPair[1].x, keyPair[1].y, E) h, s = signatureGeneration(str(ekey.x) + str(ekey.y), P, n, s_l) mes = { 'ID': stuID, 'KEYID': str(i), 'QAI.X': ekey.x, 'QAI.Y': ekey.y, 'Si': s, 'Hi': h } response = requests.put('{}/{}'.format(API_URL, "SendKey"), json=mes) print(response.json()) i = i + 1 return ephemeralKeys
def decryptAndAuth_p2(msg, curve, eph_keys): # msg = msg["MSG"] # eph_keys is the list of all ephemeral keys. T = Point(msg["QBJ.X"], msg["QBJ.Y"], curve) * eph_keys[int(msg["KEYID"])] U = (str(T.x) + str(T.y) + "NoNeedToRunAndHide") # https://www.youtube.com/watch?v=W6oQUDFV2C0&ab_channel=MatthewF. K_enc = SHA3_256.new(U.encode("utf-8")) # enc. session key K_mac = SHA3_256.new(K_enc.digest()) # mac key # print(K_enc.digest()) # print(K_mac.digest()) # message as byte array byteMsg = msg["MSG"].to_bytes((msg["MSG"].bit_length() + 7) // 8, byteorder='big') # mac is the last 32 bytes of the message big_mac = byteMsg[len(byteMsg) - 32:] # yes, big_mac is mac of the message. cip = int.from_bytes( byteMsg[:len(byteMsg) - 32], byteorder='big') # cip is the ciphertext in number format dec_arr = decrypt(cip, AES.MODE_CTR, K_enc) #print(dec_arr) msg = byteMsg[8:len(byteMsg) - 32] # first 8 byte is nonce h = HMAC.new(K_mac.digest(), digestmod=SHA256) h.update(msg) try: # return the decrypted string if msg is authentic h.verify(big_mac) print("The message '%s' is authentic" % msg) return dec_arr except ValueError: # return none if auth. fails print("The message or the key is wrong")
def CheckBlock(filename, curve): if os.path.isfile(filename): f = open(filename, "r") block = f.readlines() if len(block)%9 != 0: print("Incorrect file format") f.close() return -10000 block_count = len(block)//9 for i in range(0, block_count): # coordinates of the public key point x1 = int(block[i*9+2][22:-1]) y1 = int(block[i*9+3][22:-1]) r = int(block[i*9+7][15:-1]) s = int(block[i*9+8][15:-1]) tx = "".join(block[i*9: i*9+7]) # For the signature verfication payer = ECDSA() payer_pk = ECPublicKey(Point(x1, y1, curve)) signature = encode_sig(r, s) try: assert(payer.verify(tx.encode('UTF-8'), signature, payer_pk)) ver = 0 f.close() return ver except: ver = -i-1 f.close() return ver return 0 else: print("File does not exist") return -10000
def verify(pub_key, data, signature, hashfunc=sha256, curve=curve.P256, sign_fmt='DER', sign_size=32, pub_key_fmt='RAW'): if sign_fmt in ['RAW', 'DER']: pass else: raise UnknownSignatureFormatError("fmt: '%s'" % sign_fmt) if pub_key_fmt == 'RAW': pub_key_encoded = pub_key elif pub_key_fmt == '04': pub_key_encoded = pub_key[2:] else: raise UnknownPublicKeyFormatError("fmt: '%s'" % pub_key_fmt) x, y = split_str_to_halves(pub_key_encoded) x, y = int(x, 16), int(y, 16) pub_key_point = ECPublicKey(Point(x, y, curve)) signature = bytes.fromhex(signature) signer = ECDSAWithSize(fmt=sign_fmt, size=sign_size) msg = hashfunc(data.encode()).digest() return signer.verify(msg, signature, pub_key_point)
def KeyGen(curve): secret = secrets.randbelow(curve.order - 1) x, y = Mult_Elliptic(curve.generator.x, curve.generator.y, secret, curve) Q = Point(x, y, curve) return secret, Q
def run_pmult(self, k, Px=None, Py=None, check=True, verbose=False): """Run an arbitrary pmult. Args: Px (int): X coordinate of curve point Py (int): Y coordinate of curve point k (int): multiplier check: if set, verify the result (using ecpy) """ if Px == None: Px = self.curve.generator.x Py = self.curve.generator.y self.Px = Px self.Py = Py self.k = k self.fpga_write(self.REG_CRYPT_GX, list(int.to_bytes(Px, length=32, byteorder='little'))) self.fpga_write(self.REG_CRYPT_GY, list(int.to_bytes(Py, length=32, byteorder='little'))) self.fpga_write(self.REG_CRYPT_K, list(int.to_bytes(k, length=32, byteorder='little'))) self.go() if not self.is_done(): logging.warning("Target not done yet, increase clksleeptime!") #let's wait a bit more, see what happens: i = 0 while not self.is_done(): i += 1 time.sleep(0.05) if i > 100: logging.warning("Target still did not finish operation!") break Rx = int.from_bytes(self.fpga_read(self.REG_CRYPT_RX, 32), byteorder='little') Ry = int.from_bytes(self.fpga_read(self.REG_CRYPT_RY, 32), byteorder='little') # optionally check result: if check: P = Point(Px, Py, self.curve) Q = k * P if verbose: print("Expecting Qx = %s" % hex(Q.x)) print("Expecting Qy = %s" % hex(Q.y)) if Q.x != Rx: print("Bad Rx!") print("expected %32x" % hex(Q.x)) print("got %32x" % hex(Rx)) if Q.y != Ry: print("Bad Ry!") print("expected %32y" % hex(Q.y)) print("got %32y" % hex(Ry)) return {'Rx': Rx, 'Ry': Ry}
def find_ecc_point(x, p): found = False x -= 1 while not found: x += 1 y_sq = pow(x, 3) + 7 y = modular_sqrt(y_sq, p) if y != 0: return Point(x, y, curve)
def _(): cv = Curve.get_curve('secp256k1'); pu_key = ECPublicKey( Point(0x65d5b8bf9ab1801c9f168d4815994ad35f1dcb6ae6c7a1a303966b677b813b00, 0xe6b865e529b8ecbf71cf966e900477d49ced5846d7662dd2dd11ccd55c0aff7f, cv)) pv_key = ECPrivateKey( 0xfb26a4e75eec75544c0f44e937dcf5ee6355c7176600b9688c667e5c283b43c5, cv) ; signer = ECDSA(fmt="ITUPLE") sig = signer.sign(b'01234567890123456789012345678912', pv_key) ;return sig
def __init__(self, pubkey=None, raw=False): if USE_SECP: self.obj = secp256k1.PublicKey(pubkey, raw) else: if not raw: raise Exception("Non raw init unsupported") pubkey = pubkey[1:] x = int.from_bytes(pubkey[0:32], 'big') y = int.from_bytes(pubkey[32:], 'big') self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1))
def new_point(self, tries=100, bits=256): for i in range(tries): x = random.getrandbits(bits) y = self.curve.y_recover(x) if x > 0 and y: P = Point(x, y, self.curve, check=True) # shouldn't be necessary but let's check anwyway: assert self.curve.is_on_curve(P) return P raise ValueError("Failed to generate a random point after %d tries!" % self.tries)
def KeyGen(E): n = E.order P = E.generator sA = secrets.randbelow(n-1) x, y = EllipticMultiplication(P.x, P.y, sA, E) QA = Point(x, y, E) # print("Private Key: %d \nPublic Key X: %d \nPublic Key Y: %d" % (sA, QA.x, QA.y)) return sA, QA
def __verifyUsingPublicKey(self, signature, api_key, params, timestamp, public_key): signer = ECDSA() pu_bytes = base64.b64decode(public_key) # int(pu_bytes[1:33].encode('hex'), 16) x = int(binascii.hexlify(pu_bytes[1:33]), 16) y = int(binascii.hexlify(pu_bytes[33:]), 16) pu_key = ECPublicKey(Point(x, y, cv)) hashed = hashlib.sha256("{}.{}.{}".format( api_key, params, timestamp).encode("UTF-8")).hexdigest() return signer.verify(bytearray.fromhex(hashed), bytearray.fromhex(signature), pu_key)
def Diffie_HelmanProtocol(V, v, R, r): ''' Diffie-Helman Key exchange protocol begins. At the end of the protocol, ASharedSec == BSharedSec (c--shared secret) must be same. ''' # For Transaction initiator (Alice) px =V.x py =V.y VPoint = Point(px,py,cv) ASharedSec = cv.mul_point(r,VPoint) ASharedSecHash = sha3.keccak_256((str(cv.mul_point(r, VPoint))).encode()) AsharedSecInHexForm = ASharedSecHash.hexdigest() # For Transaction receiver (Bob) px =R.x py =R.y RPoint = Point(px,py,cv) BSharedSec = cv.mul_point(v, RPoint) BSharedSecHash = sha3.keccak_256((str(cv.mul_point(v, RPoint))).encode()) BsharedSecInHexForm = BSharedSecHash.hexdigest() if AsharedSecInHexForm == BsharedSecInHexForm: # Confirming Shared secret is same for both Alice and Bob. print("Alice's secret is ", AsharedSecInHexForm) print("Bob's secret is ", BsharedSecInHexForm) print('') #print("Alice's secret Hash is: ", ASharedSecHash) #print("Bob's secret Hash is: ", BSharedSecHash) print('') print("The Secret is the same for both Alice and Bob.") print('') else: print("The Secret is not the same.") return VPoint, RPoint
def t1(): #k = 0xa546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4 k = 31029842492115040904895560451863089656472772604678260265531221036453811406496 u = 34426434033919594451155107781188821651316167215306631574996226621102155684838 ku = cv._mul_point_x(k,u) print("ku: %x"%ku) v = cv.y_recover(ku) P = Point(ku,v,cv) eP = cv.encode_point(P) print(binascii.hexlify(eP)) Q = cv.decode_point(eP) assert(P.x == Q.x)
def receiveMessage(): h, s = signatureGeneration(str(stuID), P, n, s_l) # Get your message mes = {'ID_A': stuID, 'S': s, 'H': h} response = requests.get('{}/{}'.format(API_URL, "ReqMsg_PH3"), json=mes) print(response.json()) if (response.ok): response = response.json() idSender = response["IDB"] idEphemeral = response["KEYID"] msg = response["MSG"] QBj = Point(response["QBJ.X"], response["QBJ.Y"], E) print("Message from student " + str(idSender)) # decrypt messages sAi = ephemeralKeys[int(idEphemeral)][0] QAi = ephemeralKeys[int(idEphemeral)][1] T = sAi * QBj U = str(T.x) + str(T.y) + "NoNeedToRunAndHide" KeyEncodeAB = SHA3_256.new(U.encode()).digest() KeyMacAB = SHA3_256.new(KeyEncodeAB).digest() ctext = msg.to_bytes((msg.bit_length() + 7) // 8, byteorder='big') mac = ctext[-32:] message = ctext[8:-32] cipher = AES.new(KeyEncodeAB, AES.MODE_CTR, nonce=ctext[0:8]) dtext = (cipher.decrypt(message)).decode('UTF-8') print(dtext) hMac = HMAC.new(KeyMacAB, digestmod=SHA256) hMac.update(message) try: hMac.verify(mac) print("Message is authentic!") except ValueError: print("Message is not authentic") else: sys.exit(response.json())
def session_key_generation(curve, messageObject): keyID = messageObject["KEYID"] qB_x = messageObject["QBJ.X"] qB_y = messageObject["QBJ.Y"] # generate session keys (qBj and i is given) k_enc -> sai*qBj k_mac -> SHA3(k_enc) qA_i = Point(qB_x, qB_y, curve) sB_j = ephemeralDictionary[int(keyID)][0] T = sB_j * qA_i U = str(T.x) + str(T.y) + "NoNeedToRunAndHide" U = bytes(U, 'utf-8') # Compute the session keys k_enc = SHA3_256.new(U) k_enc = k_enc.digest() k_mac = SHA3_256.new(k_enc) k_mac = k_mac.digest() return k_enc, k_mac
def sendMessage(): h, s = signatureGeneration(str(stuID_B), P, n, s_l) mes = {'ID_A': stuID, 'ID_B': stuID_B, 'S': s, 'H': h} response = requests.get('{}/{}'.format(API_URL, "ReqKey"), json=mes) if response.ok: res = response.json() myEphemeralIndex = int(res["i"]) otherPartyEphemeralIndex = int(res["j"]) QBj = Point(res["QBJ.x"], res["QBJ.y"], E) sAi = ephemeralKeys[myEphemeralIndex][0] QAi = ephemeralKeys[myEphemeralIndex][1] T = sAi * QBj U = str(T.x) + str(T.y) + "NoNeedToRunAndHide" KeyEncodeAB = SHA3_256.new(U.encode()).digest() KeyMacAB = SHA3_256.new(KeyEncodeAB).digest() message = str(input("Enter a message to send to the client: ")) cipher = AES.new(KeyEncodeAB, AES.MODE_CTR) nonce = cipher.nonce ctext = cipher.encrypt(message.encode()) hMac = HMAC.new(KeyMacAB, digestmod=SHA256) macCode = hMac.update(ctext).digest() msg = nonce + ctext + macCode msg = int.from_bytes(msg, "big") mes = { 'ID_A': stuID, 'ID_B': stuID_B, 'I': myEphemeralIndex, 'J': otherPartyEphemeralIndex, 'MSG': msg } response = requests.put('{}/{}'.format(API_URL, "SendMsg"), json=mes) print(response.json()) else: sys.exit(response.json())
def CheckTransactions(filename, E): if os.path.isfile(filename): f = open(filename, "r") block = f.readlines() if len(block) % TxLen != 0: print("Incorrect file format") f.close() return -10000 block_count = len(block) // TxLen for i in range(0, block_count): # coordinates of the public key point x1 = int(block[i * TxLen + 2][22:-1]) y1 = int(block[i * TxLen + 3][22:-1]) r = int(block[i * TxLen + 7][15:-1]) s = int(block[i * TxLen + 8][15:-1]) tx = "".join(block[i * TxLen:i * TxLen + 7]) # For the signature verfication payer_pk = Point(x1, y1, E) if ECDSA.SignVer(tx.encode('UTF-8'), s, r, E, payer_pk) != 0: return -1 return 0 else: print("File does not exist") return -10000
sA, QA = ECDSA.KeyGen(E) # generate a secret/public key pair message = b"When you can't find the sunshine, be the sunshine" s, r = ECDSA.SignGen(message, E, sA) if ECDSA.SignVer(message, s, r, E, QA) == 0: print("Test I: The signature verifies") else: print("Test I: The signature DOES NOT verify") # Test II ######### # Testing our version of ECDSA against instructor's implementation # Verify given and signature and a public key message = b"The grass is greener where you water it" QA = Point(0x7ab5dec56a20e34df53271ca762783f676220a2ea070232f826f3039406b5d7a, 0x36f65e364f7256b351d3d8104afdfeb8db9c1a04d4e2c5b3a8d2641cf0621ed6, E) s = 4289659650376074400726941554044308237614114989665261590076669828835550338890 r = 115746559255364438191053617180138969779714428433454613098411101174935626257180 if ECDSA.SignVer(message, s, r, E, QA) == 0: print("Test II: The signature verifies") else: print("Test II: The signature DOES NOT verify") # Test III ######### # Generating random transactions signed by ECDSA TxCnt = 32 # the number of transactions in the block tx_blk = gen_random_txblock(E, TxCnt) fp = open("transactions.txt", "w") fp.write(tx_blk)
Q = s*P return s, Q def SignGen(m,sA): k = random.randint(1,n-1) R = k*P r = R.x % n hash = str.encode(str(m)) + r.to_bytes((r.bit_length()+7)//8, byteorder='big') h = SHA3_256.new(hash) h = (int.from_bytes(h.digest(), byteorder='big')) % n s = (sA*h + k) % n return h, s #create a long term key sL = 63801239034806087212362893222539508958299091046300031574693893463603277165026 QCli_long = Point(0x43ad23dc5ea14f130384d6dfa8d594dedb652c1163bba0af89a17bcebc69344 , 0x8aaa302a86c605e920bb616b21a2d6a3e2f863dacfa63d404bd2aa948b0556a2,curve) h, s = SignGen(stuID,sL) #signing the student ID #print("h is", h) #print("s is", s) ####Register Long Term Key #s, h = SignGen(str(stuID).encode(), curve, sCli_long) #using our SignGen function #mes = {'ID':stuID, 'H': h, 'S': s, 'LKEY.X': QCli_long.x, 'LKEY.Y': QCli_long.y} #response = requests.put('{}/{}'.format(API_URL, "RegLongRqst"), json = mes) #print(response.json()) #code = int(input()) #mes = {'ID':stuID, 'CODE': code} #response = requests.put('{}/{}'.format(API_URL, "RegLong"), json = mes)
from ecpy.curves import Curve, Point ed = Curve.get_curve('Ed25519') P = Point(0x3f14cc3324c79d9687f95c8f75af102eaebc1f7670a80b1f6a07959e3698afe9, 0x4a927deb79b86633dc86a0ea061ef34276dc20d736a7b47fc926e54cf4ea5e32, ed) Q = Point(0x34a511dbf0b36780d8c785ecc2857525bc990a6df9803c68b8af302be00c104c, 0x417587b30efdc587244a8609934a5ce39bf2986de45706810b0c0e314bc961f5, ed) print('-------------------------------------------------') y = int.from_bytes(ed.encode_point(P), 'big') print("P %s" % hex(y)) y = int.from_bytes(ed.encode_point(Q), 'big') print("Q %s" % hex(y)) print('-------------------------------------------------') Q_ = Point(ed.field - Q.x, Q.y, ed) Z = P + Q_ print(Z) y = int.from_bytes(ed.encode_point(Z), 'big') print(hex(y)) print('-------------------------------------------------') print('-------------------------------------------------')
_r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 _b = 0x0000000000000000000000000000000000000000000000000000000000000007 _a = 0x0000000000000000000000000000000000000000000000000000000000000000 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp(_p, _a, _b) generator_secp256k1 = ecdsa.ellipticcurve.Point(curve_secp256k1, _Gx, _Gy, _r) oid_secp256k1 = (1, 3, 132, 0, 10) SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1) ec_order = _r curve = curve_secp256k1 cv = Curve.get_curve('secp256k1') #generator = generator_secp256k1 generator = Point(_Gx, _Gy, cv) # Another way to get the G byte_array = '' def random_secret(): # Method to generate private key. byte_array = os.urandom(32) joinArray = "".join([str(i) for i in byte_array]) convert_to_int = int(joinArray) encode_int = int(hex(convert_to_int), 16) return (encode_int % ec_order) def getKeyPair(): # Now going to generate a new private key. secret = random_secret() #Generate a new private key. P = (secret * generator)
} response = requests.put('{}/{}'.format(API_URL, "SendKey"), json=mes) print(response.json()) ### Get key of the Student B m = str(stuID_B) m = str.encode(m) h1, s1 = signature_generation(n, m, P, sA_l) mes = {'ID_A': stuID, 'ID_B': stuID_B, 'S': s1, 'H': h1} response = requests.get('{}/{}'.format(API_URL, "ReqKey"), json=mes) res = response.json() print(res) i = int(res['i']) j = res['j'] QBj = Point(res['QBJ.x'], res['QBJ.y'], curve) #mesg to send #mesg = "You can dance, you can jive" #print("This is my message:", mesg) for i in range(len(test)): mesg = test[i] print("This is my message:", mesg) #calculations from pdf T = arraysA[i] * QBj U = str(T.x) + str(T.y) + "NoNeedToRunAndHide" U = str.encode(U) K_ENC = SHA3_256.new(U) K_ENC = K_ENC.digest() K_MAC = SHA3_256.new(K_ENC)
return left == right if __name__ == "__main__": try: ### EDDSA cv = Curve.get_curve('Ed25519') # public key # x: 74ad28205b4f384bc0813e6585864e528085f91fb6a5096f244ae01e57de43ae # y: 0c66f42af155cdc08c96c42ecf2c989cbc7e1b4da70ab7925a8943e8c317403d pu_key = ECPublicKey( Point( 0x74ad28205b4f384bc0813e6585864e528085f91fb6a5096f244ae01e57de43ae, 0x0c66f42af155cdc08c96c42ecf2c989cbc7e1b4da70ab7925a8943e8c317403d, cv)) # private key # s: 0x4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb pv_key = ECPrivateKey( 0x4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb, cv) # sig: # 0x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da # 0x085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00 expected_sig = int( 0x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00 ) expected_sig = expected_sig.to_bytes(64, 'big')
#Hash: # 8c7632afe967e2e16ae7f39dc32c252b3d751fa6e01daa0efc3c174e230f4617 #Signer's public: 04 # 81bc1f9486564d3d57a305e8f9067df2a7e1f007d4af4fed085aca139c6b9c7a # 8e3f35e4d7fb27a56a3f35d34c8c2b27cd1d266d5294df131bf3c1cbc39f5a91 #App signature: # 304402203a329589dbc6f3bb88bf90b45b5d4935a18e13e2cb8fcee0b94b3102ec19645702202f61af55df0e56e71d40a9f5f111faeb2f831c1fd314c55227ac44110fb33049 ### ECS # test key cv = Curve.get_curve('secp256k1') pv_key = ECPrivateKey(0xf028458b39af92fea938486ecc49562d0e7731b53d9b25e2701183e4f2adc991,cv) pu_key = ECPublicKey(Point(0x81bc1f9486564d3d57a305e8f9067df2a7e1f007d4af4fed085aca139c6b9c7a, 0x8e3f35e4d7fb27a56a3f35d34c8c2b27cd1d266d5294df131bf3c1cbc39f5a91, cv)) k = pv_key.get_public_key() assert(k.W.x == pu_key.W.x) assert(k.W.y == pu_key.W.y) print("Public key ok") msg = 0x8c7632afe967e2e16ae7f39dc32c252b3d751fa6e01daa0efc3c174e230f4617 msg = msg.to_bytes(32,'big') sig = 0x304402203a329589dbc6f3bb88bf90b45b5d4935a18e13e2cb8fcee0b94b3102ec19645702202f61af55df0e56e71d40a9f5f111faeb2f831c1fd314c55227ac44110fb33049 sig = sig.to_bytes(70,'big')
import hashlib from ecpy.curves import Curve, Point cv = Curve.get_curve('Curve25519') ed = Curve.get_curve('Ed25519') p = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed d = 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3 a = -1 x = 0x36ab384c9f5a046c3d043b7d1833e7ac080d8e4515d7a45f83c5a14e2843ce0e y = 0x2260cdf3092329c21da25ee8c9a21f5697390f51643851560e5f46ae6af8a3c9 P = Point(x, y, ed) B = 1 A = 486662 def inv(x): return pow(x % p, p - 2, p) def AB(a, d): A = (2 * (a + d) * inv(a - d)) % p B = (4 * inv(a - d)) % p print("A %x" % A) print("B %x" % B) def UV(x, y): u = ((1 + y) * inv((1 - y) % p)) % p v = ((1 + y) * inv(((1 - y) * x) % p)) % p
#Send Ephemeral keys mes = {'ID': stuID, 'KEYID': i , 'QAI.X': QA.x, 'QAI.Y': QA.y, 'Si': sx, 'Hi': hx} response = requests.put('{}/{}'.format(API_URL, "SendKey"), json = mes) print(response.json()) ### Get key of the Student B mes = {'ID_A': stuID, 'ID_B':stuID_B, 'S': s, 'H': h} response = requests.get('{}/{}'.format(API_URL, "ReqKey"), json = mes) res = response.json() print(res) i = res['i'] j = res['j'] QBj = Point(res['QBJ.X'] , res['QBJ.Y'], curve) #mesg to send mesg = "You can dance, you can jive" print("This is my message:", mesg) #calculations from pdf T = arraysA[i]*QBj U = str(T.x)+str(T.y)+"NoNeedT oRunAndHide" U = str.encode(U) K_ENC = SHA3_256.new(U) K_ENC = K_ENC.digest() K_MAC = SHA3_256.new(K_ENC) K_MAC = K_MAC.digest() # Encyption cipher = AES.new(K_ENC, AES.MODE_CTR)
xPub = b'\x03'+pu_key.W.x.to_bytes(size,'big') else : xPub = b'\x02'+pu_key.W.x.to_bytes(size,'big') hasher.update(xQ+xPub+msg) v = hasher.digest() v = int.from_bytes(v,'big') v = v%n return v == r if __name__ == "__main__": import sys,random try: cv = Curve.get_curve('NIST-P256') pu_key = ECPublicKey(Point(0x09b58b88323c52d1080aa525c89e8e12c6f40fcb014640fa88081ed9e9352de7, 0x5ccbbd189538516238b0b0b28acb5f0b5e27217c3a9872421219de0aeebf1080, cv)) pv_key = ECPrivateKey(0x5202a3d8acaf6909d12c9a774cd886f9fba61137ffd3e8e76aed363fb47ac492, cv) msg = int(0x616263) msg = msg.to_bytes(3,'big') k = int(0xde7e0e5e663f24183414b7c72f24546b81e9e5f410bebf26f3ca5fa82f5192c8) ## ISO R=0x5A79A0AA9B241E381A594B220554D096A5F09FA628AD9A33C3CE4393ADE1DEF7 S=0x5C0EB78B67A513C3E53B2619F96855E291D5141C7CD0915E1D04B347457C9601 signer = ECSchnorr(hashlib.sha256,"ISO","ITUPLE") sig = signer.sign_k(msg,pv_key,k)