def add_sign(filename,data): hs = gost34112012256.new(data).digest() print('[+] Hash: {0}'.format(gost34112012256.new(data).hexdigest())) alpha = int.from_bytes(hs, byteorder='big') e = alpha % q if e == 0: e = 1 while True: k = generate_prime(q) C = multiply(P, k, curve.a, p) r = C.x % q if r == 0: continue s = (r * d + k * e) % q if s == 0: continue encoded_bytes = encode_signature(Q, p, curve, P, q, r, s) file = open(filename + '.sign', 'wb') file.write(encoded_bytes) file.close() return True
def _check_sign(filePath, signPath): print("Checking sign of the file...") file = open(filePath, 'rb') fileData = file.read() file.close() file = open(signPath, 'rb') signData = file.read() file.close() print("---> STEP #1: Getting r,s, Q_x, Q_y from asn.1 file...") x_q, y_q, r, s = asnGenerator.decodeSign(signData) print("r = ", r) print("s = ", s) print(" Checking if (0 < r < q) & (0 < s < q)...") if ((r > 0 and r < q) and (s > 0 and s < q)): print(" r and s are OK") print("---> STEP #2: Calculating hash of the file...") h = gost34112012256.new(fileData).digest() print(' hash = {0}'.format( gost34112012256.new(fileData).hexdigest())) print("---> STEP #3: Calculating alpha from hash...") alpha = int.from_bytes(h, byteorder="big") print(" Calculating e = alpha (mod q) ...") e = alpha % q if e == 0: print(" e = 0 ---> e = 1") e = 1 else: print(" e != 0") print("---> STEP #4: Calculating v = e^(-1) (mod q) ...") v = invert(e, q) print(" v = ", v) print("---> STEP #5: Calculating z1 = s*v (mod q) ...") print(" Calculating z2 = (-r*v) (mod q) ...") z_1 = (s * v) % q z_2 = (-r * v) % q print("---> STEP #6: Calculating C = z1*P + z2*Q ...") x1, y1 = _mul_points(p_x, p_y, z_1) x2, y2 = _mul_points(x_q, y_q, z_2) x_C, y_C = sum(x1, y1, x2, y2) print(" Calculating R = C_x (mod q) ...") R = x_C % q print(" R = ", R) print("---> STEP #7: Checking if R = r ...") if R == r: print(" ! R = r !") return True else: print(" ! R != r !") return False return False
def post(self): parser = reqparse.RequestParser() for key in self.user_reg_keys: parser.add_argument(key) params = parser.parse_args() email_re = '^[a-z0-9A-ZА-Яа-я]+[\._]?[a-z0-9A-ZА-Яа-я]+[@]\w+[.]\w{2,3}$' if not re.search(email_re, params["email"]): return {"status": "Incorrect email"}, 400 phone_re = '(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})' if not re.search(phone_re, params["phone"]): return {"status": "Incorrect phone"}, 400 for key in self.user_reg_keys: if not params[key]: return {"status": "Bad arguments"}, 400 params["password"] = gost34112012256.new( salt.encode() + params["password"].encode()).hexdigest() conn = sqlite3.connect('Enigma.db') user = conn.execute("SELECT * from patient WHERE passport = {}".format( params["passport"])).fetchone() conn.close() if user: return {"status": "User exists"}, 400 fromaddr = username = '******' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username, password) token = hexlify(str(uuid4()).encode()).decode() url = "{}/user/registration?token={}".format(host, token) msg = '''Здравствуйте! Ссылка для подтверждения регистрации - {}'''.format( url) server.sendmail(fromaddr, params["email"], msg.encode()) server.quit() params["password"] = gost34112012256.new( salt.encode() + params["password"].encode()).hexdigest() conn = sqlite3.connect('Enigma.db') conn.execute( "INSERT INTO unverified_users (name,surname,email,passport,password,phone,date_birth,city,street," "num_oms, email_token) VALUES ('{}','{}','{}',{},'{}',{},'{}','{}','{}',{}, '{}')" .format(params["name"], params["surname"], params["email"], params["passport"], params["password"], params["phone"], params["date_birth"], params["city"], params["street"], params["num_oms"], str(token))) conn.commit() conn.close() return {"status": "Send register-url"}, 200
def put(self): parser = reqparse.RequestParser() for key in self.user_reg_keys: parser.add_argument(key) params = parser.parse_args() email_re = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' if not re.search(email_re, params["email"]): return {"status": "Incorrect email"} phone_re = '([+]\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})' if not re.search(phone_re, params["phone"]): return {"status": "Incorrect phone"} params["password"] = gost34112012256.new( salt.encode() + params["password"].encode()).hexdigest() conn = sqlite3.connect('Enigma.db') user = conn.execute( "SELECT id_patient from patient WHERE password = '******' AND token = '{}'" .format(params["password"], params["token"])).fetchone() conn.close() if user is None: return {"status": "Incorrect token or password"}, 400 id_patient = list(user)[0] for key in self.user_reg_keys: conn = sqlite3.connect('Enigma.db') conn.execute( "UPDATE patient set {} = '{}' where id_patient = {}".format( key, params["key"], id_patient)) conn.commit() conn.close() return {"status": "User edited"}, 200
def post(self): parser = reqparse.RequestParser() for key in self.user_reg_keys: parser.add_argument(key) params = parser.parse_args() for key in self.user_reg_keys: if params[key] is None: return {"status": "Bad arguments"}, 400 params["password"] = gost34112012256.new( salt.encode() + params["password"].encode()).hexdigest() conn = sqlite3.connect('Enigma.db') user = conn.execute( "SELECT id_patient FROM patient WHERE email = '{}' AND password = '******'" .format(params["email"], params["password"])).fetchone() conn.close() if user is None: return {"status": "Incorrect email or password"}, 400 id_patient = list(user)[0] token = uuid4() conn = sqlite3.connect('Enigma.db') conn.execute( "UPDATE patient set token = '{}' WHERE id_patient = {}".format( token, id_patient)) conn.commit() conn.close() return {"status": "User logged in", "token": str(token)}, 200
def checkSignature(self, data, signature, pubKey): dgst = gost34112012256.new(data.encode()).digest() return verify(self.curve, pub_unmarshal(hexdec(pubKey), mode=2012), dgst, hexdec(signature), mode=2012)
def verify_sign(filename): parse_file('signature') s = decoded_values[-1] r = decoded_values[-2] q = decoded_values[-3] Q_x = decoded_values[0] Q_y = decoded_values[1] p = decoded_values[2] a = decoded_values[3] P_x = decoded_values[5] P_y = decoded_values[6] with open(filename, 'rb') as file: data = file.read() hash = gost34112012256.new(data).digest() e = int.from_bytes(hash, byteorder='big') % q if e == 0: e = 1 v = invert(e, q) z_1 = s * v % q z_2 = -r * v % q tmp_1 = multiply(Point(P_x, P_y), z_1, a, p) tmp_2 = multiply(Point(Q_x, Q_y), z_2, a, p) C = add(tmp_1, tmp_2, a, p) R = C.x % q return True if R == r else False
def _sign_file(filename, x_Q, y_Q): print("Signing file...") print("d = ", d) file = open(filename, 'rb') data = file.read() file.close() print("---> STEP #1: Calculating hash...") h = gost34112012256.new(data).digest() print(' hash = ', h) print("---> STEP #2: Calculating alpha from hash...") alpha = int.from_bytes(h, byteorder="big") print(" Calculating e = alpha (mod q) ...") e = alpha % q if e == 0: print(" e = 0 ---> e = 1") e = 1 else: print(" e != 0") r = 0 s = 0 while r == 0 or s == 0: print("---> STEP #3: Calculating random k (0 < k < q) ...") k = randint(int(0), int(q)) print("---> STEP #4: Calculating C = kP...") x_C, y_C = _mul_points(p_x, p_y, k) print("---> STEP #4: Calculating r = C_x (mod q) ...") r = x_C % q if r != 0: print(" r != 0") print("---> STEP #5: Calculating s = (r*d + k*e) (mod q) ...") s = (r * d + k * e) % q if s != 0: print(" s != 0") else: print(" r = 0 ---> choosing new random k") else: print(" r = 0 ---> choosing new random k") print(" ---> Gor r, s:") print(" r = ", r) print(" s = ", s) print(" ---> Creating asn.1 file for sign ... ") sign_encoded = asnGenerator.encodeSign(x_Q, y_Q, p, a, b, p_x, p_y, q, r, s) print(" ---> Saving asn.1 file ...") file = open(filename + '.sign', 'wb') file.write(sign_encoded) file.close()
def number_from_str(family): if not isinstance(family, str): return -1 # Working only with .encode() method, else TypeError last = gost34112012256.new(family.encode()).digest()[-1] last &= 15 if last >= 10: return chr(ord('A') + last - 10) return str(last)
def add_sign(data): hash = gost34112012256.new(data).digest() print('[+] Hash: {0}'.format(gost34112012256.new(data).hexdigest())) int_hash = int.from_bytes(hash, byteorder='big') e = int_hash % q if e == 0: e = 1 while True: k = generate_prime(q) C = multiply(P, k, curve.a, p) r = C.x % q if r == 0: continue s = (r * d + k * e) % q if s == 0: continue encoded_bytes = encode_file_signature(Q, p, curve, P, q, r, s) with open('signature', 'wb') as sign: sign.write(encoded_bytes) return True
def verify_sign(filename, file_Signature): decoded_values = parse_file(file_Signature) s = decoded_values[-1] r = decoded_values[-2] q = decoded_values[-3] Q_x = decoded_values[0] Q_y = decoded_values[1] p = decoded_values[2] a = decoded_values[3] P_x = decoded_values[5] P_y = decoded_values[6] if r <= 0 or r >= q or s <= 0 or s >= q: print('[-] Invalid signature') file = open(filename, 'rb') data = file.read() file.close() hash = gost34112012256.new(data).digest() alpha = int.from_bytes(hash, byteorder='big') e = alpha % q if e == 0: e = 1 v = invert(e, q) z_1 = (s * v) % q z_2 = (-r * v) % q tmp_1 = multiply(Point(P_x, P_y), z_1, a, p) tmp_2 = multiply(Point(Q_x, Q_y), z_2, a, p) C = add(tmp_1, tmp_2, a, p) R = C.x % q if R == r: return True else: return False
def verify(self, signature, b_msg): self.dgst = gost34112012256.new(b_msg).digest() return verify(curve, self.pub, self.dgst, signature, mode=2012)
def sign(self, bmsg): dgst = gost34112012256.new(bmsg).digest() signature = sign(curve, int(self.prv), dgst, mode=2012) return signature
from pygost import gost34112012256 print( gost34112012256.new( "Батяновский Иван Тарасович".encode('utf-8')).digest().hex()[-1])
from pygost import gost34112012256 variant = gost34112012256.new( "Фирфаров Александр Сергеевич".encode('utf-8')).digest().hex()[-1] print(variant)
def createSignature(self, data, prvKey): dgst = gost34112012256.new(data.encode()).digest() return hexenc( sign(self.curve, prv_unmarshal(hexdec(prvKey)), dgst, mode=2012))