def vote(candidate_id): logging.info("\n\n\t\t---- Client: Vote -----\n") private_key, public_key = KEYS.read_my_keys() vote_crt = KEYS.read_voting_certificate() sk_voter = KEYS.read_voting_secret_key() signature = base64.b64encode( Utilities.sign_RSA(str(candidate_id), RSA.import_key(private_key))).decode('ascii') voting_data = {'vote': str(candidate_id), 'signature': signature} logging.info("Voting Data: ", voting_data) voting_data = Utilities.payload_encryptor_Fernet(voting_data, sk_voter) payload = {"data": voting_data.decode('utf-8'), "vote_crt": vote_crt} logging.info("Sending Data: ", payload) """ LOAD RSA Key of AS """ VS_RSA_Key = RSA.import_key(KEYS.load_public_key('VS-public.key')) try: response = sendRequest(data=payload, RSA_KEY=VS_RSA_Key, path="vote") message = response.get('message') print(message) logging.info(message) except Exception as e: message = "Exception #3: {}".format(e) print(message) logging.info(message)
def generate_certificaat(request): try: logging.info("\n\n\t\t---- CA receive a request -----\n") sessionKey = Utilities.payload_decryptor_RSA( request.POST["sessionKey"], load_RSA_key('CA-private.key')).encode() actual_message = Utilities.payload_decryptor_Fernet( request.POST["data"], sessionKey) logging.info("CA request actual message: {}".format(actual_message)) name = actual_message["name"] national_code = actual_message["national_code"] timestamp = actual_message["timestamp"] if national_code is None or name is None: message = 'نام یا کدملی به درستی ارسال نشده است.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) if not Utilities.check_payload_timestamp(timestamp): message = 'مهلت درخواست ارسال شده منقضی شده است.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) except Exception as e: print("#Exception-1: {}".format(e)) message = 'درخواست به درستی ارسال نشده است.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) try: userObjects = User.objects.filter(name=name, national_code=national_code) if userObjects.count() <= 0: message = 'نام یا کدملی شما معتبر نیست.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) elif userObjects.count() > 1: print("#ERROR IN SYSTEM: 2 user with same national code") message = 'لطفا با پشتیبانی تماس بگیرید.' logging.info("#ERROR IN SYSTEM: 2 user with same national code") payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) user = userObjects.first() if user: payload = create_certificaat(user, national_code) return sendResponse(payload, sessionKey) else: message = 'کاربر یافت نشد، لطفا دوباره تلاش کنید.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) except Exception as e: print("#Exception2: {}".format(e)) message = 'لطفا با پشتیبانی تماس بگیرید.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey)
def generateCertificaat(name, national_code): logging.info("\n\n\t\t---- Client: generateCertificaat -----\n") """ Set national code & name in data dic""" data = { "national_code": national_code, "name": name, "timestamp": Utilities.create_timestamp_for_payload() } logging.info("Sending Data: ", data) """ LOAD RSA Keys """ CA_RSA_Key = RSA.import_key(KEYS.load_public_key('CA-public.key')) """ Send Request to CA """ try: response = sendRequest(data=data, RSA_KEY=CA_RSA_Key, path="generate-certificaat") if response.get('status') == 'successful': myPrivateKey = response.get('private_key') myPublicKey = response.get('public_key') lifeTime = response.get('life_time') timestamp = response.get('time_stamp') signature = base64.b64decode( response.get('certificate_signature').encode('ascii')) if not Utilities.check_payload_timestamp(timestamp): message = "گواهی دریافت شده تازه نمیباشد." print(message) logging.info(message) return if Utilities.verify_certificate(national_code=national_code, public_key=myPublicKey, signature=signature, pubkey=CA_RSA_Key, lifeTime=lifeTime): if not Utilities.check_payload_lifetime(lifeTime): message = "گواهی ارسال شده منقصی شده است." print(message) logging.info(message) return message = "گواهی دریافت شده و به درستی توسط ca امضا شده است. همچنین تاریخ انقضای آن فرا نرسیده است." print(message) logging.info(message) KEYS.save_certificate_signature( response.get('certificate_signature')) KEYS.save_certificate_lifeTime(response.get('life_time')) KEYS.save_my_keys(privateKey=myPrivateKey, publicKey=myPublicKey) else: message = response.get("message") print(message) logging.info(message) except Exception as e: message = "Exception #1: {}".format(e) print(message) logging.info(message)
def checkAsCertificationSignature(sk_voter, public_key, signature): try: return Utilities.verify_AS_sign( sk_voter=sk_voter, public_key=public_key, pubkey=settings.load_public_key('AS-public.key'), signature=base64.b64decode(signature.encode('ascii'))) except Exception as e: return False
def checkVoteSignature(user_vote, pubkey): try: return Utilities.verify_vote( candidate_id=user_vote.get("vote"), pubkey=RSA.import_key(pubkey), signature=base64.b64decode( user_vote.get("signature").encode('ascii'))) except Exception as e: return False
def decodeResponse(response, RSA_KEY, Session_Key): try: data = response.get("data") data = Utilities.payload_decryptor_Fernet(data, Session_Key) except Exception as e: message = "#Exception in Decode Response: {}".format(e) print(message) logging.info(message) return data
def sendRequest(data, RSA_KEY, path): """ Generate Session Key""" Session_Key = Utilities.generate_Fernet_key() """ Encrypt Data with Session Key""" encryptedData = Utilities.payload_encryptor_Fernet(data, Session_Key) stringSession_Key = str(Session_Key, 'utf-8') encryptedSessionKey = Utilities.payload_encryptor_RSA( stringSession_Key, RSA_KEY.publickey()) encryptedSessionKey = base64.b64encode(encryptedSessionKey) """ Create payload """ payload = {"data": encryptedData, "sessionKey": encryptedSessionKey} """ Send Request """ try: response = session.post(url=BASE_URL + path, data=payload) response = response.json() return decodeResponse(response, RSA_KEY, Session_Key) except Exception as e: message = "#Exception in REQUEST: {}".format(e) print(message) logging.info(message)
def generate_AS_ticket(request): try: logging.info("\n\n\t\t---- AS receive a request -----\n") sessionKey = Utilities.payload_decryptor_RSA( request.POST["sessionKey"], load_RSA_key('AS-private.key')).encode() actual_message = Utilities.payload_decryptor_Fernet( request.POST["data"], sessionKey) logging.info("AS request actual message: {}".format(actual_message)) public_key = actual_message["public_key"] national_code = actual_message["national_code"] certificate_signature = actual_message["certificate_signature"] life_time = actual_message["lifetime"] timestamp = actual_message["timestamp"] signature = base64.b64decode( actual_message["signature"].encode('ascii')) if national_code is None: message = 'کدملی به درستی ارسال نشده است.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) if not Utilities.check_payload_timestamp(timestamp): message = 'مهلت درخواست ارسال شده منقضی شده است.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) message = json.dumps({ 'national_code': national_code, 'public_key': public_key, 'lifetime': life_time, 'certificate_signature': certificate_signature, 'timestamp': timestamp, }) if not Utilities.verify_RSA(message, signature, RSA.import_key(public_key)): message = 'امضا با کلید عمومی ارسالی مطابقت ندارد.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) if not Utilities.check_payload_lifetime(life_time): message = 'گواهی ارسالی منقضی شده است' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) if not Utilities.verify_certificate( national_code=national_code, lifeTime=life_time, public_key=public_key, signature=base64.b64decode( actual_message['certificate_signature'].encode('ascii')), pubkey=load_RSA_key('CA-public.key')): message = 'گواهی ارسالی معتبر نمیباشد.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) except Exception as e: print("#Exception-1: {}".format(e)) message = 'درخواست به درستی ارسال نشده است.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) try: restricted_users = RestrictedNationalCodes.objects.filter( national_code=national_code).count() if restricted_users > 0: message = 'متاسفانه شما مجاز به رای دادن نمیباشید.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) sk_voter = Utilities.generate_Fernet_key() # creating vote certificate # vote certificate consists of a session key which is encrypted with the public key of vs # and sk_voter || public voter || signature encrypted with session key session_key = Utilities.generate_Fernet_key( ) # session key between AS and VS message = json.dumps({ 'sk_voter': str(sk_voter, 'utf-8'), 'public_key': public_key }) AS_signature = base64.b64encode( Utilities.sign_RSA(message, load_RSA_key('AS-private.key'))).decode('ascii') data = { "status": "successful", "sk_voter": str(sk_voter, 'utf-8'), "public_key": public_key, "AS_signature": AS_signature, } encryptedData = Utilities.payload_encryptor_Fernet(data, session_key) stringSession_Key = str(session_key, 'utf-8') encryptedSessionKey = Utilities.payload_encryptor_RSA( stringSession_Key, load_RSA_key('VS-public.key')) encryptedSessionKey = base64.b64encode(encryptedSessionKey).decode( 'ascii') encryptedData = base64.b64encode(encryptedData).decode('ascii') vote_crt = json.dumps({ 'data': encryptedData, 'sessionKey': encryptedSessionKey }) new_timestamp = Utilities.create_timestamp_for_payload() message = json.dumps({ 'status': 'successful', 'sk_voter': str(sk_voter, 'utf-8'), 'vote_crt': vote_crt, 'time_stamp': new_timestamp }) AS_signature = base64.b64encode( Utilities.sign_RSA(message, load_RSA_key('AS-private.key'))).decode('ascii') message = 'بلیت و کلید رای دهی با موفقیت ارسال شد.' logging.info(message) payload = { 'message': message, 'status': 'successful', 'sk_voter': str(sk_voter, 'utf-8'), 'vote_crt': vote_crt, 'time_stamp': new_timestamp, 'signature': AS_signature } return sendResponse(payload, sessionKey) except Exception as e: print("#Exception2: {}".format(e)) message = 'لطفا با پشتیبانی تماس بگیرید.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey)
def sendResponse(data, key): """ Encrypt Data with Session Key""" encryptedData = Utilities.payload_encryptor_Fernet(data, key) encryptedData = encryptedData.decode('utf-8') """ Return Response """ return JsonResponse({"data": encryptedData}, status=200)
def create_certificaat(user, national_code): certificaat = Certificaat.objects.filter(user=user) if certificaat.count() == 1: certificaat = certificaat.first() private_key = certificaat.private_key public_key = certificaat.public_key life_time = certificaat.life_time message = json.dumps({ 'national_code': national_code, 'public_key': public_key, 'life_time': life_time }) sig = base64.b64encode( Utilities.sign_RSA(message, load_RSA_key('CA-private.key'))).decode('ascii') message = 'گواهی شما ارسال شد.' logging.info(message) payload = { 'status': 'successful', 'message': message, 'private_key': private_key, 'public_key': public_key, 'certificate_signature': sig, 'life_time': life_time, 'time_stamp': Utilities.create_timestamp_for_payload() } return payload else: while True: # preventing to create a repetitive key private_key, public_key = Utilities.generate_RSA_key() certificaatWithSameRSAKeys = Certificaat.objects.filter( private_key=private_key) if certificaatWithSameRSAKeys.count() == 0: break life_time = Utilities.create_lifetime_for_payload() certificate = Certificaat(user=user, private_key=private_key, public_key=public_key, life_time=life_time) certificate.save() message = json.dumps({ 'national_code': national_code, 'public_key': public_key, 'life_time': life_time }) sig = base64.b64encode( Utilities.sign_RSA(message, load_RSA_key('CA-private.key'))).decode('ascii') message = 'گواهی با موفقیت ایجاد شد.' logging.info(message) payload = { 'status': 'successful', 'message': message, 'private_key': private_key, 'public_key': public_key, 'certificate_signature': sig, 'life_time': life_time, 'time_stamp': Utilities.create_timestamp_for_payload() } return payload
import pandas as pd import xgboost as xgb sys.path.append("../src") from base import Utilities, Config from common import CustomTransformation config = Config() train_module = CustomTransformation(config, 'train') watchlist = [(train_module.ddata, 'train')] print(train_module.final_columns) params = Utilities.load_json(config.params_file) history = xgb.cv(params, train_module.ddata, 300, early_stopping_rounds=30, metrics=["auc", "error"], verbose_eval=True) model = xgb.train(params, train_module.ddata, 200, verbose_eval=True) class_mapping = Utilities.load_json(config.class_mapping_file) test_module = CustomTransformation("test", class_mapping, train_module.final_columns) y_pred = model.predict(test_module.ddata) submission_df = pd.DataFrame({config.notable_columns["ID"]: list(test_module.main_column.values), config.notable_columns["Target"]: list(y_pred)}) submission_df.to_csv(os.path.join(config.home, 'submission', 'one.csv'), float_format='%0.6f', index=False) xgbfir.saveXgbFI(model, feature_names=train_module.final_columns, TopK=500, SortBy='Gain', \ MaxTrees=500, MaxInteractionDepth=2, OutputXlsxFile='XGBoost-FI.xlsx')
def vote(request): try: logging.info("\n\n\t\t---- VS: vote receive a request -----\n") """ Read Request Data """ sessionKey = Utilities.payload_decryptor_RSA( request.POST["sessionKey"], load_RSA_key('VS-private.key')).encode() actual_message = Utilities.payload_decryptor_Fernet( request.POST["data"], sessionKey) logging.info("VS request actual message: {}".format(actual_message)) """ Read Vote Certificate Data """ vote_crt = json.loads(actual_message.get("vote_crt")) logging.info("VS request vote_crt : {}".format(vote_crt)) AS_sessionKey = Utilities.payload_decryptor_RSA( vote_crt.get('sessionKey'), load_RSA_key('VS-private.key')) vote_crt_data = base64.b64decode(vote_crt.get('data').encode('ascii')) vote_crt_data = Utilities.payload_decryptor_Fernet( vote_crt_data, AS_sessionKey.encode()) vote_crt_status = vote_crt_data.get("status") vote_crt_sk_voter = vote_crt_data.get("sk_voter") vote_crt_user_public_key = vote_crt_data.get("public_key") vote_crt_AS_signature = vote_crt_data.get("AS_signature") logging.info("SK Voter : {}".format(vote_crt_sk_voter)) logging.info("User Public Key : {}".format(vote_crt_user_public_key)) logging.info("AS Signature : {}".format(vote_crt_AS_signature)) """ Read Vote Data """ vote_data = actual_message.get("data").encode() user_vote = Utilities.payload_decryptor_Fernet( vote_data, vote_crt_sk_voter.encode()) logging.info("User Vote : {}".format(user_vote)) except Exception as e: print("#Exception-1: {}".format(e)) logging.info("#Exception-1: {}".format(e)) payload = { 'status': 'fail', 'message': 'درخواست به درستی ارسال نشده است.' } return sendResponse(payload, sessionKey) try: """ Check AS Certification """ if not checkAsCertificationSignature( sk_voter=vote_crt_sk_voter, public_key=vote_crt_user_public_key, signature=vote_crt_AS_signature): message = 'امضای گواهی AS معتبر نمیباشد.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) """ Check Vote """ if vote_crt_status != "successful": message = 'مشکلی در حالت توکن ارسالی وجود دارد.' logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) if not checkVoteSignature(user_vote=user_vote, pubkey=vote_crt_user_public_key): message = "امضای رای داده شده با کلید عمومی موجود در توکن مطابقت ندارد." logging.info(message) payload = {'status': 'fail', 'message': message} return sendResponse(payload, sessionKey) payload = addVote(candidate_id=user_vote.get("vote"), public_key=vote_crt_user_public_key) return sendResponse(payload, sessionKey) except Exception as e: print("#Exception-2: {}".format(e)) logging.info("#Exception-2: {}".format(e)) payload = { 'status': 'fail', 'message': 'درخواست به درستی ارسال نشده است.' } return sendResponse(payload, sessionKey)
import xgboost as xgb from base import Config, Utilities from common import CustomTransformation config = Config() train_module = CustomTransformation(config, 'train') # watchlist = [(train_module.ddata, 'train')] params = Utilities.load_json(config.params_file) print(len(train_module.final_columns)) model = xgb.cv(params, train_module.ddata, 300, early_stopping_rounds=30, metrics=["auc", "error"], verbose_eval=True) #model = xgb.cv(params, train_module.ddata, 100, early_stopping_rounds=10, verbose_eval=True)
def generate_AS_ticket(national_code): logging.info("\n\n\t\t---- Client: generate_AS_ticket -----\n") private_key, public_key = KEYS.read_my_keys() certificate_signature = KEYS.read_certificate_signature() lifetime = KEYS.read_certificate_lifeTime() timestamp = Utilities.create_timestamp_for_payload() message = json.dumps({ 'national_code': national_code, 'public_key': public_key, 'lifetime': lifetime, 'certificate_signature': certificate_signature, 'timestamp': timestamp, }) signature = base64.b64encode( Utilities.sign_RSA(message, RSA.import_key(private_key))).decode('ascii') data = { "national_code": national_code, "public_key": public_key, "lifetime": lifetime, "certificate_signature": certificate_signature, "timestamp": timestamp, "signature": signature } logging.info("Sending Data: ", data) """ LOAD RSA Key of AS """ AS_RSA_Key = RSA.import_key(KEYS.load_public_key('AS-public.key')) """ Send Request to AS """ try: response = sendRequest(data=data, RSA_KEY=AS_RSA_Key, path="generate-AS-ticket") if response.get('status') == 'successful': sk_voter = response.get('sk_voter') vote_crt = response.get('vote_crt') timestamp = response.get('time_stamp') signature = base64.b64decode( response.get('signature').encode('ascii')) if not Utilities.check_payload_timestamp(timestamp): message = "گواهی دریافت شده تازه نمیباشد." print(message) logging.info(message) return message = json.dumps({ 'status': 'successful', 'sk_voter': sk_voter, 'vote_crt': vote_crt, 'time_stamp': timestamp }) if not Utilities.verify_RSA(message, signature, AS_RSA_Key): message = "جواب دریافت شده معتبر نمیباشد." print(message) logging.info(message) return message = "بلیت و کلید رای دهی دریافت شد. برای اطمینان از کارکرد آن لطفاً اقدام به رای دهی نمایید." print(message) logging.info(message) KEYS.save_voting_certificate(vote_crt) KEYS.save_voting_secret_key(sk_voter) else: message = response.get('message') print(message) logging.info(message) except Exception as e: message = "Exception #2: {}".format(e) print(message) logging.info(message)