Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import numpy as np
- import random
- import os.path
- from simplecrypt import encrypt,decrypt
- from Crypto.Hash import SHA
- from Crypto.Util import number
- prime_value_q = number.getPrime(160)
- maxFeatures=0
- stDev=2
- mean=10
- history_file_name=""
- newUser = True
- h = 5
- ti =10
- class Poly:
- coeff = []
- def __init__(self, coeff):
- self.coeff = coeff
- def val(self, x):
- sum_val = 0
- for i, value in enumerate(self.coeff):
- sum_val = sum_val + value*pow(x, i)
- return sum_val
- def poly_gen(m_minustwo,hpwd):
- coefficient = [hpwd] + random.sample(xrange(100), m_minustwo)
- return Poly(coefficient)
- def alphaTrue(pswd, i, coeffList):
- i=i+1
- #Get SHA
- sha = SHA.new(str(2*i) + pswd).hexdigest()
- #Format SHA from str to long
- fmtSHA = long(''.join([str(ord(h)) for h in sha]))
- #calc Alpha Value
- A=coeffList.val(2*i) + (fmtSHA % prime_value_q)
- #print "ALPHA ", coeffList.val(2*i)
- #print "ALPHA %s %s %s %s" % (i, (2 * i), pswd, fmtSHA)
- return A
- def alphaFalse(pswd, i):
- pswd=pswd + str(random.randrange(0, 1000))
- i=i + 1
- coeffList = poly_gen(maxFeatures - 5, random.randrange(0, prime_value_q - 1))
- # Get SHA
- sha = SHA.new(str(2 * i) + pswd).hexdigest()
- # Format SHA from str to long
- fmtSHA = long(''.join([str(ord(h)) for h in sha]))
- # calc Alpha Value
- A = coeffList.val(2 * i) + (fmtSHA % prime_value_q)
- return A
- def betaTrue(pswd, i, coeffList):
- i=i+1
- #Get SHA
- sha = SHA.new(str(2*i+1) + pswd).hexdigest()
- #print "SHA:",sha
- #Format SHA from str to long
- fmtSHA = long(''.join([str(ord(h)) for h in sha]))
- #calc Beta Value
- B=coeffList.val(2*i+1) + (fmtSHA % prime_value_q)
- #print "BETA ", coeffList.val(2*i+1)
- #print "BETA %s %s %s %s" % (i, (2 * i + 1), pswd, fmtSHA)
- return B
- def betaFalse(pswd, i):
- pswd=pswd + str(random.randrange(0, 1000))
- i=i + 1
- coeffList = poly_gen(maxFeatures - 5, random.randrange(0, prime_value_q - 1))
- # Get SHA
- sha = SHA.new(str(2 * i+1) + pswd).hexdigest()
- # Format SHA from str to long
- fmtSHA = long(''.join([str(ord(h)) for h in sha]))
- # calc Beta Value
- B = coeffList.val(2 * i+1) + (fmtSHA % prime_value_q)
- return B
- def instrTblGenerator(pswd, featuresList):
- instrTbl=[]
- avgFeatureSpeed = np.mean(featuresList, axis=0)
- sigma = np.std(featuresList, axis=0)
- hpwd = random.randrange(0, prime_value_q - 1)
- #print "encrypt " , hpwd
- coeffList = poly_gen(maxFeatures - 1, hpwd)
- for i in range(maxFeatures):
- if ((i < len(avgFeatureSpeed)) and ((abs(avgFeatureSpeed[i] - mean) - 0.0001) > (stDev * sigma[i]))):
- #print "mean:%s avg spd:%s"%(mean,avgFeatureSpeed[i])
- if (avgFeatureSpeed[i] < mean):
- # Fast: beta=Random alpha=TRUE
- #print "ALPHA FAST"
- A=alphaTrue(pswd, i, coeffList)
- B = betaFalse(pswd, i)
- instrTbl.append([A, B])
- # print "Alpha:%s Beta: %s"%(A,B)
- else:# SLOW: beta=TRUE alpha=Random
- #print "BETA FAST"
- A = alphaFalse(pswd, i)
- B = betaTrue(pswd, i, coeffList)
- instrTbl.append([A, B])
- # print "Alpha:%s Beta: %s" % (A, B)
- else:# Neither: beta=TRUE alpha=TRUE
- #print "mean:%s avg spd:%s" % (mean, avgFeatureSpeed[i-1])
- #print "SAME"
- A = alphaTrue(pswd, i, coeffList)
- B = betaTrue(pswd, i, coeffList)
- instrTbl.append([A, B])
- #print "Alpha:%s Beta: %s\n" % (A, B)
- return [hpwd, instrTbl]
- #CHANGE UP
- def DecryptFromFile(key):
- with open(history_file_name+'.hf', 'rb') as f:
- cipher_text = f.read()
- pad, plain_text = decrypt(key, cipher_text).split("````")
- return plain_text
- def hist_gen(hpwd,featuresList):
- features2str = ''
- for i in xrange(1, len(featuresList)):
- features2str += ','.join([str(j) for j in featuresList[i]]) + '\n'
- paddedfeatures2str = "````" + features2str
- strhpwd=SHA.new(str(hpwd)).hexdigest()
- ciphertext = encrypt(strhpwd, paddedfeatures2str.rjust(800, '^'))
- file = open((history_file_name+".hf"), "w")
- file.write(ciphertext)
- file.close()
- '''def file_parser(inFile):
- global maxFeatures
- i=0
- featuresList =[]
- while i < len(inFile):
- pswd=inFile[i]
- i = i + 1
- #convert features from string to int
- features = map(int,inFile[i].split(','))
- if (len(pswd) - 2 != len(features)):
- print 'Feature and password do not match!'
- sys.exit()
- maxFeatures = len(pswd) - 1
- featuresList.append(features)
- i = i + 1
- return pswd,featuresList'''
- #CHANGE UP
- def lamb(x_array,i):
- mult = 1
- for j in range(len(x_array)):
- if j!=i:
- mult = mult*(x_array[j]/(x_array[j]-x_array[i]))
- return mult
- #CHANGE UP
- #this is our Lagrange function, which takes x,y pairs and q to recreate hpwd
- def Lagrange(x_array, y_array):
- sum = 0
- for i in range(len(y_array)):
- #this calls the lambda function which creates uses the x values to create the coefficient to multiply y with
- lam = lamb(x_array,i)
- #this is where we sum the array
- sum = sum + (lam * y_array[i])
- return sum
- # lagrange interpolation to get h_pwd from xy values
- def h_pwdLagrange(x,y, feature_num):
- h_pwd = 0
- nums = []
- dens = []
- dens_sum = 1
- for i in xrange(0, feature_num):
- lambda_num = 1
- lambda_den = 1
- for j in xrange(0, feature_num):
- if (i != j):
- lambda_num *= x[j]
- lambda_den *= x[j] - x[i]
- nums.append(lambda_num * y[i])
- dens.append(lambda_den)
- for i in xrange(0, len(nums)):
- h_pwd += get_Num(i, nums, dens)
- dens_sum *= dens[i]
- return h_pwd/dens_sum # floor division to avoide float conversion
- #used to minimize the divisions
- def get_Num(index, nums, dens):
- num = 1
- for i in xrange(0, len(nums)):
- if i == index:
- num *= nums[i]
- else:
- num *= dens[i]
- return num
- def login(features,instrTbl,password):
- ys=[]
- alphas = []
- betas = []
- xs = []
- # parse the instruction table to list of alpha and list of beta
- i = 1
- j = 0
- # password = alpha if features < ti , password = beta if features>=ti
- for f in features:
- if f < ti:
- sha = SHA.new(str(2 * i) + password).hexdigest()
- sha = long(''.join([str(ord(h)) for h in sha]))
- p = instrTbl[j][0] - sha % prime_value_q
- #print "Decrypt alph ", p
- #print "Decrypt alph %s %s %s %s" %( i, (2 * i), password, sha)
- ys.append(p)
- xs.append(2*i)
- else:
- sha = SHA.new(str(2 * i + 1) + password).hexdigest()
- sha = long(''.join([str(ord(h)) for h in sha]))
- p = instrTbl[j][1] - sha % prime_value_q
- #print "Decrypt beta ", p
- #print "Decrypt beta %s %s %s %s" % (i, (2 * i+1), password, sha)
- ys.append(p)
- xs.append(2*i+1)
- i = i + 1
- j = j + 1
- hpwd = h_pwdLagrange(xs, ys,maxFeatures)
- #print "decreypt " , hpwd
- featuresList = []
- try:
- inst = DecryptFromFile(SHA.new(str(hpwd)).hexdigest()).strip()
- instList = inst.split("\n")
- #print "hist ", instList
- if len(instList) == 6:
- instList = instList[1:]
- #print instList
- for i in instList:
- features = i.split(',')
- features = map(int, features)
- featuresList.append(features)
- #print featuresList
- return featuresList
- #features = content[i].split(',')
- # print features
- #features = map(int, features)
- except:
- return featuresList
- '''def main(inFileName,hisfilename):
- global history_file_name, newUser
- history_file_name=hisfilename
- if os.path.exists((hisfilename+".hf")):
- newUser=False
- else:
- with open(inFileName, 'r') as inFile:
- pswd, featuresList = file_parser(inFile.readlines())
- print pswd, featuresList
- if not newUser:
- login(pswd)
- else:
- hpwd, instrTbl = instrTblGenerator(pswd, featuresList)
- hist_gen(hpwd, featuresList)'''
- def main(filename):
- global maxFeatures, history_file_name
- featuresList=[]
- instrTbl=[]
- try:
- with open(filename, 'r') as f:
- content = f.read()
- #this is to handle the header!!! delete this if its not neccessary
- #content = content.split("\outl0\strokewidth0 \strokec2 ")[1][:-1]
- #########
- content = content.split()
- except:
- print("filename: " + filename + " is incorrect!")
- return
- i = 0
- j = 1
- while i < len(content):
- password = content[i]
- maxFeatures = len(password) - 1
- i = i + 1
- features = content[i].split(',')
- #print features
- features = map(int, features)
- #print "ooooo ", j
- #print "features ", features
- #print "Feature new ", featuresList
- if j <= h:
- #print "features lest ", len(featuresList)
- featuresList.append(features)
- print "1"
- if j == h:
- #print "i equals to h "
- #create_inst
- hpwd, instrTbl = instrTblGenerator(password, featuresList)
- #creat_hist
- history_file_name = filename.split(".")[0]
- hist_gen(hpwd, featuresList)
- if j > h:
- #print "feature list size ", len(featuresList)
- #print "i is fuck " ,i
- # if length of login return m_features is not 0
- #and then we are going to pass m_features to make a new hist and inst
- newFeaturesList = login(features,instrTbl,password)
- if len(newFeaturesList) != 0:
- print("1")
- featuresList = newFeaturesList
- featuresList.append(features)
- hpwd, instrTbl = instrTblGenerator(password, featuresList)
- hist_gen(hpwd, featuresList)
- else:
- print("0")
- i = i + 1
- j = j + 1
- if __name__ == '__main__':
- main(sys.argv[1:][0])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement