Пример #1
0
def test2():
    client = UdpEndPoint()
    p = UdpEndPoint()
    group_object = PairingGroup('SS512')
    key_client = group_object.random(GT)
    key_p = group_object.random(GT)
    nonce = OpenSSLRand().getRandomBits(128)
    server_crypter_a = SymmetricCryptoAbstraction(extractor(key_client))
    server_crypter_b = SymmetricCryptoAbstraction(extractor(key_p))
    c_package_a = test1(client, p, nonce,
                        objectToBytes(key_client, group_object),
                        objectToBytes(key_p, group_object))
    print('===========================================================')
    print(c_package_a)
    key_package_a = server_crypter_a.decrypt(c_package_a)
    key_package_a = bytesToObject(key_package_a, group_object)
    key_package_b = server_crypter_b.decrypt(key_package_a[3])
    key_package_b = bytesToObject(key_package_b, group_object)
    print('===========================================================')
    i = 1
    for thing in key_package_a:
        print(str(i) + '.', thing)
        i += 1
    print('===========================================================')
    j = 1
    for thing in key_package_b:
        print(str(j) + '.', thing)
        j += 1
    print('===========================================================')
Пример #2
0
def deserialize(storage):
	storage['n'] = storage['n']
	storage['master_public_key'] = bytesToObject(storage['master_public_key'], group)
	storage['master_key'] = bytesToObject(storage['master_key'], group)
	storage['plain'] = bytesToObject(storage['plain'], group)
	storage['cipher'] = bytesToObject(storage['cipher'], group)
	return storage
Пример #3
0
def deserialize(storage):
    storage['n'] = storage['n']
    storage['master_public_key'] = bytesToObject(storage['master_public_key'],
                                                 group)
    storage['master_key'] = bytesToObject(storage['master_key'], group)
    storage['plain'] = bytesToObject(storage['plain'], group)
    storage['cipher'] = bytesToObject(storage['cipher'], group)
    return storage
Пример #4
0
	def resetKeys(self, keyMap):
		''' Reset the master/public keys for all of the ciphers that are being used by 
		the system right now.
		'''
		self.master = bytesToObject(keyMap['mk'], self.groupObj)
		self.public = bytesToObject(keyMap['pk'], self.groupObj)
		for c in self.cipherQueue:
			c.setKeys(self.master, self.public)
Пример #5
0
 def __init__(self, uid):
     self.group = GROUP
     self.gs_protocol = eval(GS_PROTOCOL)(self.group)
     self.path = f'parameters/{GS_PROTOCOL.lower()}'
     gpk_path = os.path.join(self.path, 'public/gpk')
     self.gpk = bytesToObject(open(gpk_path, 'rb').read(), self.group)
     sk_path = os.path.join(self.path, f'users/{uid:02d}/sk')
     self.sk = bytesToObject(open(sk_path, 'rb').read(), self.group)
Пример #6
0
    def enrollment(self, pw):
        response = self._requestobj.get("%s/enroll" % self._endpoint, verify = False)
        document = response.json()
        c0    = bytesToObject(document["c0"],    group)
        c1    = bytesToObject(document["c1"],    group)
        ns    = bytesToObject(document["ns"],    group)
        proof = bytesToObject(document["proof"], group)

        return self._client.do_enrollment(pw, ns, (c0,c1), proof)
def tally_vote():

	#initialization
	group = RSAGroup()
	pai = pkenc_paillier99.Pai99(group)	


	#get voting public key	
	f=open('./pyssss/VotingPublic','rb')
	data = f.read()
	public_key = bytesToObject(data,group)
	n=public_key['n']
	
	#get voting private key
	f=open('./pyssss/VotingPrivate','rb')
	data = f.read()
	secret_key = bytesToObject(data,group)

	
	#get ciphervotes file
	f=open('./CipherVotes','r')
	data=f.readlines()
	count = 0

	#open file for publishing results
	f=open('./PublishedResults','w')
	
	#go through all recorded ciphervotes
	print '#, ciphervote, plainvote'
	for vote in data:
		serializedVote = vote.strip()
		ciphervote = specialInt.deserialize(serializedVote)
		ciphervote = Ciphertext({'c':ciphervote},public_key,'c')	
		if count == 0:
			ciphertotal = ciphervote
		else:
			ciphertotal=ciphertotal+ciphervote


		#publish
		print str(count)+','+str(ciphervote['c'])+','+ str(pai.decrypt(public_key,secret_key,ciphervote)) 
		f.write(str(count)+','+str(ciphervote['c'])+','+ str(pai.decrypt(public_key,secret_key,ciphervote))+'\n' )
	
		count = count +1		

	print 'Our calculated total:', pai.decrypt(public_key,secret_key,ciphertotal)
	#get ciphervotes file
	f=open('./CipherVotesTotal','r')
	data=f.read()
	data=data.strip()
	ciphervotetotal = specialInt.deserialize(data)
	ciphervotetotal = Ciphertext({'c':ciphervotetotal},public_key,'c')
	ciphervotetotal = pai.decrypt(public_key,secret_key,ciphervotetotal)
	
	print 'Their calculated total:',ciphervotetotal

	return
Пример #8
0
 def verify(self, msg, signature, time_period, rl):
     signature = bytesToObject(signature, self.group)
     rl = [bytesToObject(rt, self.group) for rt in rl]
     if GS_PROTOCOL == 'ShortSig':
         return self.is_valid(msg) and \
                self.gs_protocol.verify(self.gpk, msg, signature)
     elif GS_PROTOCOL == 'VLRSig':
         return self.is_valid(msg) and \
                self.gs_protocol.verify(self.gpk, msg, signature, time_period, rl)
Пример #9
0
def policy(request, p_id):
	user = Policy.objects.get(pk=int(p_id))
	appname = "privateBook"
	statuses_decrypted = []
	if request.method == 'POST':
		content = request.POST.get('status', False)
		if content:
			try:
				auth = Authority.objects.get(app_name=appname)
			except ObjectDoesNotExist:
				auth = False
			if auth:
				private = bytesToObject(auth.p_key, groupObj)
				decoder = bytesToObject(auth.d_key, groupObj)
				encrypt = hyb_abe.encrypt(private, str(content), str(user.policy))
				print "-----------------------------------------------------"
				print "The status update is:"
				print content
				print "-----------------------------------------------------"
				print "Encrypted data, E is:"
				print encrypt
				print "--------------------------"
				print "And it is stored as:"
				print objectToBytes(encrypt, groupObj)
				print "-----------------------------------------------------"
				print "The decryption key is:"
				print decoder
				encrypt_b = objectToBytes(encrypt, groupObj)
				p = PostedData(p_id=int(p_id), status=encrypt_b)
				p.save()
			else:
				return render(request, 'policy.html', {'msg': 'The authority has not created any keys for you to encrypt your data!', 'id': p_id, 'name': user.name})
			return HttpResponseRedirect('')
		else:
			return render(request, 'policy.html', {'msg': 'You didn\'t enter a status. Please try again.', 'id': p_id, 'name': user.name})

	try:
		auth = Authority.objects.get(app_name=appname)
	except ObjectDoesNotExist:
		auth = False
	if auth:
		statuses = PostedData.objects.filter(p_id=int(p_id))
		for s in statuses:
			status_cipher = bytesToObject(s.status, groupObj)
			private = bytesToObject(auth.p_key, groupObj)
			decoder = bytesToObject(auth.d_key, groupObj)
			try:
				status_pair = (hyb_abe.decrypt(private, decoder, status_cipher), s.posted)
			except:
				status_pair = ("Your status could not be displayed: this service does not support your privacy policy!", s.posted)
			statuses_decrypted.append(status_pair)
	if statuses_decrypted:
		context = {'statuses': statuses_decrypted, 'id': p_id, 'name': user.name}
	else:
		context = {'id': p_id, 'name': user.name}		
	return render(request, 'policy.html', context)
Пример #10
0
def decrypt_seed_key_len(enc_seed_key_len=None, pk_file=None, sk_file=None, debug=0):
    """
    Decrypt encrypted seed, symmetric key and re-encryption length with ABE using the given public and secret key.
    :param enc_seed_key: encrypted seed, symmetric key and re-encryption length to decrypt
    :param pk_file: ABE public key
    :param sk_file: ABE secret key
    :param debug: if 1, prints will be shown during execution; default 0, no prints are shown
    :return: decrypted seed, symmetric key and number of re-encryption length
    """

    import logging
    import os.path

    # Check if enc_seed_key is set
    if enc_seed_key_len is None:
        logging.error('decrypt_seed_key ciphertext exception')
        if debug:  # ONLY USE FOR DEBUG
            print('EXCEPTION in decrypt_seed_key ciphertext')
        raise Exception

    # Check if pk_file is set and it exists
    if pk_file is None or not os.path.isfile(pk_file):
        logging.error('[ERROR] decrypt_seed_key pk_file exception')
        if debug:  # ONLY USE FOR DEBUG
            print('EXCEPTION in decrypt_seed_key pk_file')
        raise Exception

    # Check if sk_file is set and it exists
    if sk_file is None or not os.path.isfile(sk_file):
        logging.error('decrypt_seed_key sk_file exception')
        if debug:  # ONLY USE FOR DEBUG
            print('EXCEPTION in decrypt_seed_key sk_file')
        raise Exception

    # Decrypt data with ABE
    pairing_group = pg.pairing_group_create('MNT224')
    with open(pk_file, 'rb') as f:
        pk = bytesToObject(f.read(), pairing_group)
    with open(sk_file, 'rb') as f:
        sk = bytesToObject(f.read(), pairing_group)
    # cpabe = AC17CPABE(pairing_group, 2)
    cpabe = CPabe_BSW07(pairing_group)
    enc_data = cpabe.decrypt(pk, sk, enc_seed_key_len)

    from re_enc_engine.const import H, SYM_KEY_DEFAULT_SIZE, SEED_LENGTH
    import struct

    # Retrieve params from decryption output file
    seed, key, re_enc_length = struct.unpack('%ds%dsH' % (SEED_LENGTH, SYM_KEY_DEFAULT_SIZE), enc_data)

    if debug:  # ONLY USE FOR DEBUG
        print('DECRYPTED SEED = (%d) %s' % (len(seed), seed))
        print('DECRYPTED KEY = (%d) %s' % (len(key), key))
        print('DECRYPTED RE_ENC_LENGTH = %d' % re_enc_length)

    return seed, key, re_enc_length
Пример #11
0
 def __init__(self):
     self.group = PairingGroup('MNT224')
     self.gs_protocol = eval(GS_PROTOCOL)(self.group)
     self.path = f'parameters/{GS_PROTOCOL.lower()}'
     gpk_path = os.path.join(self.path, 'public/gpk')
     self.gpk = bytesToObject(open(gpk_path, 'rb').read(), self.group)
     gmsk_path = os.path.join(self.path, 'gm/gmsk')
     self.gmsk = bytesToObject(open(gmsk_path, 'rb').read(), self.group)
     dic_path = os.path.join(self.path, 'gm/identity.pkl')
     self.dic = pickle.load(open(dic_path, 'rb'))
Пример #12
0
def deserialize(storage):
    kac = KAC()
    kac.n = storage['n']
    storage['param'] = bytesToObject(storage['param'], group)
    storage['e_g1_g2'] = bytesToObject(storage['e_g1_g2'], group)
    kac.e_g1_g2 = storage['e_g1_g2']
    storage['key'] = bytesToObject(storage['key'], group)
    storage['plain'] = bytesToObject(storage['plain'], group)
    storage['cipher'] = bytesToObject(storage['cipher'], group)

    return storage
Пример #13
0
 def augment_search(n, predicate_scheme, group_name, matrix_str, generator_bytes, token_bytes, pp,
                    start_index, end_index):
     prox_scheme = ProximitySearch(n + 1, predicate_scheme, group_name)
     prox_scheme.deserialize_key(matrix_str, generator_bytes)
     prox_scheme.public_parameters = pp
     with open("ciphertexts_" + str(start_index) + "_" + str(end_index), "rb") as enc_file:
         prox_scheme.enc_data = bytesToObject(enc_file.read(), prox_scheme.predinstance.group)
         enc_file.close()
     token = bytesToObject(token_bytes, prox_scheme.predinstance.group)
     indices = prox_scheme.search(token)
     return [x+start_index for x in indices]
Пример #14
0
def deserialize(storage):
	kac = KAC()
	kac.n = storage['n']
	storage['param'] = bytesToObject(storage['param'], kac.group)
	storage['e_g1_g2'] = bytesToObject(storage['e_g1_g2'], kac.group)
	kac.e_g1_g2 = storage['e_g1_g2']
	storage['key'] = bytesToObject(storage['key'], kac.group)
	storage['plain'] = bytesToObject(storage['plain'], kac.group)
	storage['cipher'] = bytesToObject(storage['cipher'], kac.group)

	return storage
Пример #15
0
def connect(server, port):
    try :
        server.connect((host, port))
        policy = server.recv(4096)
        print('Received room policy from server: {}'.format(policy))
        pk = bytesToObject(server.recv(4096), groupObj)
        cpkey = bytesToObject(server.recv(4096), groupObj)
        print('Key attributes:  {}'.format(cpkey['attributes']))
        return pk, cpkey, policy
    except :
        print 'Unable to connect'
        sys.exit()
Пример #16
0
def receiveEncapsulations() :
    #sys.stdout.write("\n\nReceived encapsulations ")
    encapsulations = []
    for i in xrange(0,int(data[7])): 
        try: 
            encapsulations.append(bytesToObject(server.recv(4096), groupObj))
            #sys.stdout.write(str(i+1) + ", ")
        except:
            print("RECEIVE ENCAP EXCEPTION ON RUN # {}, RETRYING ONCE".format(i))
            encapsulations.append(bytesToObject(server.recv(4096), groupObj))
            continue
    print('\nEncapsulations received: {}. Generating session key.'.format(len(encapsulations)-1))
    return encapsulations 
def readFilePkMk(groupObj):

    f1 = open("private/pk_bytes", "rb")
    f2 = open("private/mk_bytes", "rb")

    pk = f1.read()
    mk = f2.read()

    orig_pk = bytesToObject(pk, groupObj)
    orig_mk = bytesToObject(mk, groupObj)
    f1.close()
    f2.close()
    return(orig_pk,orig_mk)
    def keygen(self, serPK, serMK, attributeList):
        if attributeList is None \
        or not(isinstance( attributeList, list)):
            raise Exception("attributeList must be set and a list!")

        PK = bytesToObject(serPK, self.groupObj)
        MK = bytesToObject(serMK, self.groupObj)
        
        SK = self.cpabe.keygen(PK, MK, attributeList)

        serSK = objectToBytes(SK, self.groupObj)
        
        return serSK
Пример #19
0
    def read(self, recordType):
        if recordType.lower() == "general":
            ID = self.General[0]
        elif recordType.lower() == "medical":
            ID = self.Medical[0]
        elif recordType.lower() == "training":
            ID = self.Training[0]
        else:
            print("Please enter the correct record type")
            return

        # 1. Read MySql Database to obtain string object
        # 2. Re-construct Ciphertext by converting it to a byte object, then call Charm's deSerialisation API
        # 3. Pass reconstructed ciphertext to dec() function to get plaintext
        #####################
        #MD: Todo: Add date checking
        #####################
        db = Database()
        rows = db.selectRecord(ID) # Now fetch the ciphertexts and verify the signatures and print the result
        for row in rows :
            ctI_bytes = bytes(row[0], 'utf-8')              # Integer element of CT
            ctI_Reconstruct = deserialize(ctI_bytes)
            ctPg_bytes = bytes(row[1], 'utf-8')             # PairingGroup element of CT
            ctReconstruct = bytesToObject(ctPg_bytes, self.group)
            ctReconstruct['C']['C'] = ctI_Reconstruct       # Complete Ciphertext from Integer and Pairing Group element
            pt = self.dec(recordType, ctReconstruct) # Decrypt the Ciphertext
            signerID = row[2] # get the id of the signer
            sig_bytes = bytes(row[3], 'utf-8')
            signature = bytesToObject(sig_bytes, self.signGroup) # Got the actual signature
            signdate = row[4]

            if self.verifySig(signerID, signdate, pt, signature):
                # Signature is valid, now check if entity was authorised at this date
                # Dont check our own data since we know it's valid if the signature checks out (we are always allowed to write to our own HealthRecord)
                if signerID == self.ID:
                    print("Verified record from ", signerID, ": ", pt, "\n")
                else:
                    rows = db.getAuthorisedEntities(self.ID, recordType, signdate)
                    if rows:
                        for row in rows:
                            if signerID == row[0]:
                                print("Verified record from ", signerID, ": ", pt, "\n")
                            else:
                                print("INVALID record from ", signerID, ": ", pt, "\n")
                    else:
                        #There were no authorisations for this date
                        print("INVALID record from ", signerID, ": ", pt, "\n")
            else:
                print("INVALID signature from ", signerID, ": ", pt, "\n")

        db.done()
Пример #20
0
def test1(client, p, nonce, key_client, key_p):
    group_object = PairingGroup('SS512')
    shared_key = group_object.random(GT)
    crypter_a = SymmetricCryptoAbstraction(
        extractor(bytesToObject(key_client, group_object)))
    crypter_b = SymmetricCryptoAbstraction(
        extractor(bytesToObject(key_p, group_object)))
    package_b = crypter_b.encrypt(
        objectToBytes([shared_key, serialize_endpoint(client)], group_object))
    package_a = crypter_a.encrypt(
        objectToBytes([
            Conversion.OS2IP(nonce), shared_key,
            serialize_endpoint(p), package_b
        ], group_object))
    return package_a
Пример #21
0
 def __init__(self):
     self.group = GROUP
     self.gs_protocol = eval(GS_PROTOCOL)(self.group)
     self.path = f'parameters/{GS_PROTOCOL.lower()}'
     gpk_path = os.path.join(self.path, 'public/gpk')
     self.gpk = bytesToObject(open(gpk_path, 'rb').read(), self.group)
     gmsk_path = os.path.join(self.path, 'gm/gmsk')
     self.gmsk = bytesToObject(open(gmsk_path, 'rb').read(), self.group)
     if GS_PROTOCOL == 'ShortSig':
         dic_path = os.path.join(self.path, 'gm/identity.pkl')
         self.dic = pickle.load(open(dic_path, 'rb'))
     elif GS_PROTOCOL == 'VLRSig':
         tokens_path = os.path.join(self.path, 'gm/tokens')
         self.tokens = bytesToObject(
             open(tokens_path, 'rb').read(), self.group)
Пример #22
0
    def validation(self, pw, t, n):
        nc, ns = n

        c0 = self._client.get_validation(t, pw, nc)

        payload = {'c0': objectToBytes(c0, group),
                   'ns': objectToBytes(ns, group)}

        response = self._requestobj.get("%s/validate" % self._endpoint, params=payload, verify = False)
        document = response.json()

        return self._client.do_validation(t, pw, ns, nc,
                                          bytesToObject(document['c1'],    group),
                                          bytesToObject(document['proof'], group),
                                          document['result'])
Пример #23
0
 def decode_data(self, data):
     try:
         enc_data = utils.bytesToObject(data, self._groupObj)
     except:
         print('!!!__ERROR__!!!  Ошибка decode_data')
         return {'!!!__ERROR__!!!  Ошибка decode_data'}
     return enc_data
Пример #24
0
    def _load_abe_keys(self, abe_keys_file):
        """Load public and private abe keys"""

        if self.debug:
            print("Loading abe keys from " + abe_keys_file)
        with open(abe_keys_file, 'r') as f:
            data = json.load(f)

        self.abe_pk = {}
        self.abe_sk = {}
        for abe_key_pair in data.keys():
            self.abe_pk[abe_key_pair] = bytesToObject(
                bytes.fromhex(data[abe_key_pair]['pk']), self.pairing_group)
            self.abe_sk[abe_key_pair] = bytesToObject(
                bytes.fromhex(data[abe_key_pair]['sk']), self.pairing_group)
        self.cpabe = CPabe_BSW07(self.pairing_group)
Пример #25
0
 def revokeAuthorisedEntity(self, EntityID, HealthRecordType):
     # First check if this entity is authorised
     db = Database()
     date = time.strftime("%Y-%m-%d %H:%M:%S")
     rows = db.getAuthorisedEntities(self.ID, HealthRecordType, date) #Get all authorised entities that are authorised after 1999
     if rows:
         for row in rows:
             if EntityID == row[0]:
                 found = True
                 # Found the entity for this specific recordType. Check signature
                 DateStart = row[1]
                 signature = bytesToObject(bytes(row[2], 'utf-8'), self.signGroup)
                 if(self.verifySig(self.ID, DateStart, ''.join(self.ID + EntityID + HealthRecordType), signature)):
                     # Valid signature found, now revoke it by setting the DateEnd to today and re-signing
                     # First we need to wait 1 second otherwise the script is too fast!
                     time.sleep(1)
                     DateEnd = time.strftime("%Y-%m-%d %H:%M:%S")
                     # mPK_bytes = db.getSignPubKey("master")              # bytes of the master public key
                     # mPK = bytesToObject(mPK_bytes, self.signGroup)  # de-serialize the key before usage
                     signature = objectToBytes(self.waters.sign(self.masterPK, self.signK, ''.join(self.ID + EntityID + HealthRecordType + DateEnd)), self.signGroup)
                     db.revokeAuthorisedEntity(self.ID, EntityID, HealthRecordType, DateEnd, signature)
                     print("Access for ", EntityID, " to write to ", HealthRecordType, " successfully revoked.")
                 else:
                     print("INVALID signature on authorisations")
         if found == False:
             print("Authorisation for ", EntityID, " to write to ", self.ID, "'s ", HealthRecordType, " data not found")
     else:
         print("Error: no authorisations found for ", self.ID, "'s ", HealthRecordType, " data!")
     db.done()
Пример #26
0
 def receive_msg(self, sender, msg):
     #print msg[0]
     if msg[0] in ["READY", "ECHO", "VAL"]:
         self.queues["rb"].put((sender, msg))
     if msg[0] == "send":
         self.rbfinished = True
         message = ast.literal_eval(msg[1])
         self.encshares = message['shares']
         self.encwitnesses = message['witnesses']
         self.share = self.decrypt(self.sharedkey,
                                   message['shares'][self.nodeid])
         self.witness = self.decrypt(self.sharedkey,
                                     message['witnesses'][self.nodeid])
         self.commit = bytesToObject(message['commit'], self.group)
         #if self.pc.verify_eval(self.commit, self.nodeid, self.share, self.witness):
         #    self.send_ok_msgs()
         #    self.sendrecs = True
         #else:
         #    self.send_implicate_msgs()
         self.send_implicate_msgs()
         self.finished = True
         while not self.queues["hbavss"].empty():
             (i, o) = self.queues["hbavss"].get()
             self.receive_msg(i, o)
     if not self.rbfinished:
         self.queues["hbavss"].put((sender, msg))
     elif msg[0] == "ok":
         #TODO: Enforce one OK message per participant
         self.okcount += 1
         if self.okcount == 2 * self.t + 1:
             self.output = self.share
             #print self.share
             if self.reconstruction and self.sendrecs:
                 self.send_rec_msgs()
                 self.sendrecs = False
         if self.okcount == self.k and not self.reconstruction:
             self.finished = True
     elif msg[0] == 'implicate':
         if self.check_implication(int(sender), msg[1], msg[2]):
             self.implicatecount += 1
             if self.implicatecount == 2 * self.t + 1:
                 print "Output: None"
                 self.share = None
                 self.finished = True
             if self.sendrecs:
                 self.reconstruction = True
                 self.send_rec_msgs()
                 self.sentdrecs = False
         else:
             self.okcount += 1
     elif msg[0] == 'rec':
         if self.pc.verify_eval(self.commit, sender, msg[1], msg[2]):
             self.shares[sender] = msg[1]
         if len(self.shares) == self.t + 1:
             coords = []
             for key, value in self.shares.iteritems():
                 coords.append([key, value])
             self.secret = interpolate_at_x(coords, 0, self.group)
             print self.secret
             self.finished = True
Пример #27
0
def loadDictDataFromFile(verifyParamFilesDict, groupParamArg):
    verifyArgsDict = {}
    totalNumSigs = len(verifyParamFilesDict)
    verifyFuncArgs = list(verifyParamFilesDict[0].keys())

    for sigIndex in range(0, totalNumSigs):
        verifyArgsDict[sigIndex] = {}
        for arg in verifyFuncArgs:
            verifyArgsDict[sigIndex][arg] = {}
            verifyParamFile = str(verifyParamFilesDict[sigIndex][arg])
            if (verifyParamFile.endswith(charmPickleSuffix)):
                verifyParamPickle = open(verifyParamFile, 'rb').read()
                verifyArgsDict[sigIndex][arg][bodyKey] = bytesToObject(
                    verifyParamPickle, groupParamArg)

            elif (verifyParamFile.endswith(pythonPickleSuffix)):
                verifyParamPickle = open(verifyParamFile, 'rb')
                verifyArgsDict[sigIndex][arg][bodyKey] = pickle.load(
                    verifyParamPickle)
            elif (verifyParamFile.endswith(repeatSuffix)):
                verifyArgsDict[sigIndex][arg][sigNumKey] = verifyParamFile[0:(
                    len(verifyParamFile) - lenRepeatSuffix)]
            else:
                tempFile = open(verifyParamFile, 'rb')
                tempBuf = tempFile.read()
                verifyArgsDict[sigIndex][arg][bodyKey] = tempBuf

    return verifyArgsDict
def get_vote():
	vote = raw_input("Enter your vote: ")	#get vote from user
	vote = long(vote)	
	

	#Initial setup for Paillier
	group = RSAGroup()
	pai = pkenc_paillier99.Pai99(group)

	#Get public voting public key	
	f=open("./pyssss/VotingPublic")
	data = f.read()
	public_key = bytesToObject(data,group)
	
	#Encryption with Paillier
	vote = pai.encode(public_key['n'],vote)
	ciphervote = pai.encrypt(public_key,vote)

#	ciphervotestr = str(str(ciphervote['c']).split('mod')[0])


#	print ciphervote['c']
	ciphervote = specialInt.serialize(ciphervote['c'])

	
	#pad vote
	while (len(ciphervote) < voteSize):
		ciphervote += " "

	print ciphervote
        return ciphervote
Пример #29
0
def init(persistence=b''):
    global state
    state = {}

    try:
        if persistence is None or persistence == b'':
            emb.log('ERROR: No persistence value provided. Things may not work correctly.\n')
        else:
            emb.log('Using passed in persistence value.\n')

            state['groupObj'] = PairingGroup('SS512')
            tmp = util.bytesToObject(persistence, state['groupObj'])
            state.update(tmp)

            state['dabe'] = dabe_aw11.Dabe(state['groupObj'])
            state['hyb_abema'] = dabenc_adapt_hybrid.HybridABEncMA(state['dabe'], state['groupObj'])
            state['gp']['H'] = lambda x: state['groupObj'].hash(x, G1)

            emb.log('Loaded state.\n')
            return

    except Exception:
        emb.log('ERROR: Exception while trying to load persistence value. Things may not work correctly.\n')

    state['groupObj'] = PairingGroup('SS512')
    state['dabe'] = dabe_aw11.Dabe(state['groupObj'])
    state['hyb_abema'] = dabenc_adapt_hybrid.HybridABEncMA(state['dabe'], state['groupObj'])
    state['gp'] = state['hyb_abema'].setup()
    state['authority_sk'] = {}
    state['authority_pk'] = {}
    state['user_sk'] = {}

    emb.log('Created state\n')
Пример #30
0
def parseFromXML(xmlObjectString, group=None):
    assert type(xmlObjectString) == str, "Invalid type for XML object"
    dom = parseString(xmlObjectString)
    assert dom.documentElement.tagName == "charm", "Not a Charm element"
    #    print(dom.toprettyxml(indent="  "))

    groupObj = dom.getElementsByTagName("group")
    assert groupObj != None, "Error: could not find group tag."
    groupObj = groupObj[0]
    charmObj1 = dom.getElementsByTagName("object")
    assert charmObj1 != None, "Error: could not find object tag."
    charmObj1 = charmObj1[0]

    structure = {}
    setting = groupObj.getAttribute("setting")
    param = groupObj.getAttribute("param")

    charmObj2 = dom.getElementsByTagName("name")
    structure['name'] = None
    if charmObj2 != None:
        charmObj2 = charmObj2[0]  # what is this useful for?
        structure['name'] = charmObj2.getAttribute("id")

    bytesObj = getText(charmObj1.childNodes).strip()

    if setting == 'pairing' and group == None:
        group = PairingGroup(param)
    elif structure['setting'] == 'elliptic_curve' and group == None:
        group = ECGroup(param)
    elif structure['setting'] == 'integer':
        # TODO: this is a special case
        pass
    return bytesToObject(bytesObj, group)
Пример #31
0
def parseFromXML(xmlObjectString, group=None):
    assert type(xmlObjectString) == str, "Invalid type for XML object"
    dom = parseString(xmlObjectString)
    assert dom.documentElement.tagName == "charm", "Not a Charm element"    
#    print(dom.toprettyxml(indent="  "))

    groupObj = dom.getElementsByTagName("group")
    assert groupObj != None, "Error: could not find group tag."
    groupObj = groupObj[0]
    charmObj1 = dom.getElementsByTagName("object")
    assert charmObj1 != None, "Error: could not find object tag."
    charmObj1 = charmObj1[0]
    
    structure = {}       
    setting = groupObj.getAttribute("setting")
    param = groupObj.getAttribute("param")
    
    charmObj2 = dom.getElementsByTagName("name")
    structure['name'] = None
    if charmObj2 != None: 
        charmObj2 = charmObj2[0] # what is this useful for?
        structure['name'] = charmObj2.getAttribute("id")
    
    bytesObj = getText(charmObj1.childNodes).strip()
    
    if setting == 'pairing' and group == None:
        group = PairingGroup(param)
    elif structure['setting'] == 'elliptic_curve' and group == None:
        group = ECGroup(param)
    elif structure['setting'] == 'integer':
        # TODO: this is a special case
        pass 
    return bytesToObject(bytesObj, group)
Пример #32
0
def loadDictDataFromFile(verifyParamFilesDict, groupParamArg):
    verifyArgsDict = {}
    totalNumSigs = len(verifyParamFilesDict)
    verifyFuncArgs = list(verifyParamFilesDict[0].keys())

    for sigIndex in range(0, totalNumSigs):
        verifyArgsDict[sigIndex] = {}
        for arg in verifyFuncArgs:
            verifyArgsDict[sigIndex][arg] = {}
            verifyParamFile = str(verifyParamFilesDict[sigIndex][arg])
            if (verifyParamFile.endswith(charmPickleSuffix)):
                verifyParamPickle = open(verifyParamFile, 'rb').read()
                verifyArgsDict[sigIndex][arg][bodyKey] = bytesToObject(verifyParamPickle, groupParamArg)

            elif (verifyParamFile.endswith(pythonPickleSuffix)):
                verifyParamPickle = open(verifyParamFile, 'rb')
                verifyArgsDict[sigIndex][arg][bodyKey] = pickle.load(verifyParamPickle)
            elif (verifyParamFile.endswith(repeatSuffix)):
                verifyArgsDict[sigIndex][arg][sigNumKey] = verifyParamFile[0:(len(verifyParamFile) - lenRepeatSuffix)]
            else:
                tempFile = open(verifyParamFile, 'rb')
                tempBuf = tempFile.read()
                verifyArgsDict[sigIndex][arg][bodyKey] = tempBuf

    return verifyArgsDict
	def decrypt(self, sKey, serializedCiphertext):
		''' Decrypt the provided ciphertext sing the secret key. Decryption is only successful if
		the policy embedded in the secret key matches the ciphertext access policy.

		NOTE: there is a bug in Charm (?) where a policy of a single value causes an error to be thrown: 

		unsupported right operand types: int, bytes, str

		Sample code that throws the error: 
		enc2 = EncryptionModule()
		policy = '(three)' 
		attrs = ['ONE', 'TWO', 'THREE']
		msg = "Hello world!"
		ct2 = enc2.encrypt(msg, policy)
		sk2 = enc2.generateUserKey(attrs) 
		enc2.decrypt(sk2, ct2)

		'''
		ciphertext = bytesToObject(serializedCiphertext, self.groupObj)
		c1, c2 = ciphertext['c1'], ciphertext['c2']
		success = True
		try:
			key = self.cpabe.decrypt(self.public, sKey, c1)
			if (key == False):
				success = False
		except:
			success = False

		# Try to perform the decryption if we were able to recover the key
		plaintext = None
		if (success == True):
			cipher = AuthenticatedCryptoAbstraction(sha1(key))
			plaintext = cipher.decrypt(c2)
		return (success, plaintext)
Пример #34
0
def cpabe_decrypt(group, mpk, deckey, ctxt):
    """Decrypts a ciphertext using the Bethencourt2007cae CP-ABE Scheme.
    The plaintext will be returned iff the policy used to generate the
    cipher-text can be satisfied by the set of attributes within the
    decryption key.
    @param group The `PairingGroup` used within the underlying crypto.
    @param mpk The Master Public Key of type `mk_t`.
    @param deckey The decryption key of type `sk_t`.
    @param ctxt The `bytearray` resulting from io.open or io.IOBytes
                 containing the ciphertext.
    @return The `bytearray` containing the plaintext.
    @throws PebelDecryptionException If deckey cannot satisfy the
            policy within the ciphertext.
    """
    cpabe = CPabe_BSW07(group)
    ptxt = io.BytesIO()

    iv = ctxt.read(AES.block_size)
    session_key_size = struct.unpack('<Q', ctxt.read(struct.calcsize('Q')))[0]
    session_key_ctxt = bytesToObject(ctxt.read(session_key_size), group)

    session_key = cpabe.decrypt(mpk,deckey, session_key_ctxt)

    if session_key:
        symcipher = AES.new(sha(session_key)[0:32], AES.MODE_CFB, iv)
        for b in read_data(bin_data=ctxt, chunksize=AES.block_size):
            ptxt.write(symcipher.decrypt(b))
            ptxt.flush()
        return ptxt.getvalue()
    else:
        raise PebelDecryptionException("Unable to decrypt given cipher-text.")
Пример #35
0
    def testECGroup(self):    
        groupObj = ECGroup(prime192v1)
        p=groupObj.random()
        data={'p':p,'String':"foo",'list':[p,{},1,1.7, b'dfa',]}

        x=objectToBytes(data,groupObj)
        data2=bytesToObject(x,groupObj)
        self.assertEqual(data,data2)
Пример #36
0
    def testPairingGroup(self):    
        groupobj = PairingGroup('SS512')
        p=groupobj.random()
        data={'p':p,'String':"foo",'list':[p,{},1,1.7, b'dfa',]}

        x=objectToBytes(data,groupobj)
        data2=bytesToObject(x,groupobj)
        self.assertEqual(data,data2)
 def refresh(self, serPK, serMK):
     """
     return tupel: (serPK', serMK', conversionFactor)
     """
     PK = bytesToObject(serPK, self.groupObj)
     MK = bytesToObject(serMK, self.groupObj)
     
     newAlpha = self.groupObj.random(ZR)
     PK['e_gg_alpha'] = pair(PK['g'], PK['g2'] ** newAlpha)
     g2_newAlpha = PK['g2'] ** newAlpha
     conversionFactor = ((g2_newAlpha / MK['g2_alpha']) ** ~(MK['beta'])) 
     MK['g2_alpha'] =g2_newAlpha 
     
     newSerPK = objectToBytes(PK, self.groupObj)
     newSerMK = objectToBytes(MK, self.groupObj)
     
     return (newSerPK, newSerMK, conversionFactor)
Пример #38
0
def asym_decrypt(ct_list, key):
    public_key, private_key = key
    decrypter = RSA_Enc()
    serial_pt = b''
    for ciphertext in ct_list:
        serial_pt += decrypter.decrypt(public_key, private_key, ciphertext)
    #end for
    return bytesToObject(serial_pt, IntegerGroup())
Пример #39
0
    def testIntegerGroup(self):    
        self.maxDiff=None
        groupObj = IntegerGroup()
        p = integer(148829018183496626261556856344710600327516732500226144177322012998064772051982752493460332138204351040296264880017943408846937646702376203733370973197019636813306480144595809796154634625021213611577190781215296823124523899584781302512549499802030946698512327294159881907114777803654670044046376468983244647367)
        data={'p':p,'String':"foo",'list':[p,{},1,1.7, b'dfa']}

        x=objectToBytes(data,groupObj)
        data2=bytesToObject(x,groupObj)
        self.assertEqual(data,data2)
Пример #40
0
def read_key_from_file(fname, group):
    """Utility function to read charm crypto objects from disk.
    @param fname The name of the file (`str`) containing the keys.
    @param group The `PairingGroup` used within the underlying crypto.
    @return A object reconstructed from the file.
    """
    with io.open(fname, 'rb') as f:
        data = f.read()
    return bytesToObject(data, group)
Пример #41
0
 def decryptPKenc(self, params, public_key, secret_key, cid):
     Xbytes = pkenc.decrypt(public_key, secret_key, cid['C3'])
     X = bytesToObject(Xbytes, group)          
     m = cid['C2']/pair(cid['C1'],group.hash(X,G1))            
     if(debug):
         print('\nDecrypting...')
         print('m=>')
         print(m)
     return m
Пример #42
0
 def decryptPKenc(self, params, public_key, secret_key, cid):
     Xbytes = pkenc.decrypt(public_key, secret_key, cid['C3'])
     X = bytesToObject(Xbytes, group)
     m = cid['C2'] / pair(cid['C1'], group.hash(X, G1))
     if (debug):
         print('\nDecrypting...')
         print('m=>')
         print(m)
     return m
Пример #43
0
def verify(serial_data_and_sig, public_key):
    verifier = RSA_Sig()
    data_and_sig = bytesToObject(serial_data_and_sig, IntegerGroup())
    data, sig = data_and_sig
    sig = Conversion.IP2OS(sig)
    verdict = verifier.verify(public_key, data, sig)
    if verdict == True:
        return data
    else:
        return None
Пример #44
0
 def open(self, msg, signature, time_period, patient_list=None):
     signature = bytesToObject(signature, self.group)
     if GS_PROTOCOL == 'ShortSig':
         identifier = self.gs_protocol.open(self.gpk, self.gmsk, msg,
                                            signature)
         identity = self.dic[objectToBytes(identifier, self.group)]
     if GS_PROTOCOL == 'VLRSig':
         identity = self.gs_protocol.open(self.gpk, self.tokens, signature,
                                          time_period, patient_list)
     return identity
def main():
    groupObj = PairingGroup('SS512')
    cpabe = CPabe_BSW07(groupObj)
    abe = HybridABEnc(cpabe, groupObj)



    f1 = open("private/pk_bytes", "rb")
    f2 = open("private/mk_bytes", "rb")

    pk = f1.read()
    mk = f2.read()

    orig_pk = bytesToObject(pk, groupObj)
    orig_mk = bytesToObject(mk, groupObj)


    print(orig_pk)
    
    
    # (pk,mk) = create_pk_mk_abe(abe)
  
    
    attrs1 = ['CANHTUAN','DUY','MANH']
    attrs2 = ['CANHTUAN','DUY']
    msg = "canhtuan".encode('utf-8')
    # policy = create_policy_abe(attrs2)
    policy = '(CANHTUAN and DUY and MANH)'
    # print(policy)
    


    sk2 = create_scret_key(abe,orig_pk,orig_mk,attrs1)
    ct = encrypt_abe(abe,orig_pk,"tuan".encode('utf-8'), policy)
    # print(ct)
    ct =b'eJydV9tuFEcQ/ZXVPiXSSpme6Us1Eg+WgRjFxomAkIuj1d5srNjE8S5OiOV/z1TVOTMbnmIeMDs91XU9darmfroK0yeT++nhfHd5td7Y7/l8dbXYbufz/mm6/LTbbKezSX96t7j6uLHTX1OYTZLMJqFpZ5PazCax9gf9Yen6/0v/om31bZ5NpH+qvaiopL5p+oekb0PUP50eJZcxdaFRXb3OrNJBXLFeN6Up+YGJSYfTnNx26Q9jfy9naCsqGuClag1NLxb1Xqh+KgLPQoCYve1PSq+lVn3ofxT6pq5EgdumTo2Uht72YQkdDAGBqN4s8NaC0cg1mCL+thRoM9OhbXBblWs46mLShCZktkR6J27RUqixima2Ka5TCxApZvJNcC0pU5MqaPyfvbXQihpqA293cMqtRLzTXGnEFpt6r0pjYTjZ4RBZ5YSM6lv3RTxCTWi0IsCyFBgtzE2gYbWpPmnBNe5EU+aRZzkAKZn5GWKwgJNb1SyoBk2l1a2DB+5sSxD2l3P47aFvg8P/2yLWEeKli1RiENPqVGTccqw4FTQOPanMhQXK8hHeoSE6rMxWdNPttZXhZeu49ZolgNKhqkjOLqx41EMtgqYvwxGtQUE9tFqaxAgF+ttAlNiCqHVlk6lmNW43hLXOHt8YeEvYN7xY6xi2/jMoNMB1ROY0DeZ3cqXqs5ZSmYC1+uTcdvDq6M3bg1ePrZylVtUa3Sj0S/cZyJ1mEplFKJcc8t5B9ioiU1offSUDA1X0XkHRJIMCtBIabaG43nUWEm8CYSO0gHHHejTwSwCHAiIZ/LTcgk30utUFudezSkGjauNlJUGi2Vo+A8MRxctoamu8ocaZ+A0uEYmRlkRjkEv/Kd2ztz8/vlwgaU9gO1jo3IKCx7MX4XMAjH1OAcsJlGkkg0idVIHKPNB6oi1h40FeTSV4QrIaRoIhqvh1Q0DhWLCcVTBT3GutYVaMQwwTU614/jFF1IzRL2NzaigYCsaAAeQIRm0QZAMYYAiFcXQMGS1hTI6z4liyk77NHk2OIJaIKSJpn/0YbBjmWseCCWuZ3ecyEki7Pzwrku2jLiAC2Yt2aOMAJHI8JULbiNt0t4CBs1nDRSSPTBoJf8weafbGZ4QzNmYD23xcgYSFHP8kMIOCJmPHSoCGcJsqmMqCgvhiwmUpCk/JXhnjzDny5otIUh1LWJwUswnrkqXesB6YZWHTVQYEJuCmpGgqwjIQa3Wc+ZV1Jfc69rAaZuyLBeNaANQEShHseIWDc6hqYbIiGNHExCWM6riOZSwMvqWSAcCzWCjcqQLe0WISFeZVhwat+zYzRzIw5OlLgKNaq4RC5X74ZTTJgmExSG4mAzLKIyns7c1mPxGe5CzPWtjrQiHFSt2bPYkiXj8UyjfQhhRaMGITeDvhS6GgnuPaH2bjipG5DHgDYhePXPoqdgYXI8tHdIlgF01Yamw/TvgE4FRsh5syTizjw8JPh5ZfFZ6dRGAxcZ4n0tFns+0xRDlUzR3CjmM4wvZfuBkI15AQR3Bp/tLA6aokcyhkEtDQuoHLQoRKUBPZLmJdKfvdWYTzfWgmkOcwG20VgmnPLncVKJKhl+yDpzolDKTlGOMctg0jsksCSThwSSJLdvgi5Ori61wlH8e9zySDRDNMkI7Ce3XTwt38cXW50p1yut3dPvmKlDlZfFhP+k60/7W4X2sZF7vd7eXyoxa1r6PdGDh25hq0e/HTMGHoWLWGjcXVBQ0dnRwczl8fHbQqfL0dzu/PpgfH3571j73XZ9OT02fP9aHVh5c/6s+zaXj952U5X9+9OL+9fv8yfvfh8Pt//rp4+vRsqlKHlzfvN7dvNn/vXLpcv/jh9OLu3Tf1+KdfTt8dL3/f7p6b9IPaXl9ebLY7ml+vz3PThFo3a1mcr2RRZJmkxLJOZZVWZbWspe3Cqp7Lsqs1rmPMZbFq16GGssx5+vDwL/EqTB0='
    

    giaima = decrypt_abe(abe,orig_pk, sk2, ct)
    print(giaima)

# main()
Пример #46
0
def read_key_from_file(fname, group):
    """Utility function to read charm crypto objects from disk.

    @param fname The name of the file (`str`) containing the keys.
    @param group The `PairingGroup` used within the underlying crypto.

    @return A object reconstructed from the file.
    """
    with io.open(fname, 'rb') as f:
        data = f.read()
    return bytesToObject(data, group)
Пример #47
0
    def testIntegerGroup(self):
        self.maxDiff = None
        groupObj = IntegerGroup()
        p = integer(
            148829018183496626261556856344710600327516732500226144177322012998064772051982752493460332138204351040296264880017943408846937646702376203733370973197019636813306480144595809796154634625021213611577190781215296823124523899584781302512549499802030946698512327294159881907114777803654670044046376468983244647367
        )
        data = {'p': p, 'String': "foo", 'list': [p, {}, 1, 1.7, b'dfa']}

        x = objectToBytes(data, groupObj)
        data2 = bytesToObject(x, groupObj)
        self.assertEqual(data, data2)
Пример #48
0
    def deserialize_key(self, matrix_str, generator_bytes):
        (Bstr, Bstarstr, gparams) = str.split(matrix_str, '\n')
        B = ipe.parse_matrix(Bstr, self.group)
        Bstar = ipe.parse_matrix(Bstarstr, self.group)

        (g1len, g2len) = str.split(gparams, ' ')
        g1bytes = generator_bytes[:int(g1len)]
        g2bytes = generator_bytes[int(g1len):]
        self.g1 = bytesToObject(g1bytes, self.group)
        self.g2 = bytesToObject(g2bytes, self.group)

        pp = ()
        self.B = B
        self.Bstar = Bstar
        self.public_parameters = pp

        assert self.g1.initPP(
        ), "ERROR: Failed to init pre-computation table for g1."
        assert self.g2.initPP(
        ), "ERROR: Failed to init pre-computation table for g2."
 def refreshSK(self, serSK, conversionFactor):
     '''
     refreshes the SK by the conversion_factor
     return newSerSK
     '''
     #{ 'D':D, 'Dj':D_j, 'Djp':D_j_pr, 'S':S }
     
     SK = bytesToObject(serSK, self.groupObj) 
     SK['D'] = SK['D'] *  conversionFactor
     
     return objectToBytes(SK, self.groupObj)
Пример #50
0
 def decrypt(self, key, ciphertext):
     decryptor = AES.new(objectToBytes(key, self.group)[:32], AES.MODE_CBC, 'This is an IV456')
     plaintext_bytes = decryptor.decrypt(ciphertext)
     #now we need to strip the padding off the end
     #if it's stupid but it works...
     elementsize = len(objectToBytes(self.group.random(ZR), self.group))
     paddingsize = (16 -elementsize%16)%16
     #print len(plaintext_bytes)
     #plaintext_bytes = plaintext_bytes[:len(plaintext_bytes) - paddingsize]
     #print len(plaintext_bytes)
     return bytesToObject(plaintext_bytes, self.group)
def encrypt(message, access_policy, debug=True):
    groupObj = PairingGroup('SS512')
    cpabe = CPabe_BSW07(groupObj)
    hyb_abe = HybridABEnc(cpabe, groupObj)

    with open("p_key.txt", "rb") as pkFile:
        pk = bytesToObject(pkFile.read(), groupObj)

    with open("m_key.txt", "rb") as mkFile:
        mk = bytesToObject(mkFile.read(), groupObj)

    ct = hyb_abe.encrypt(pk, message, access_policy)
    byte_msg = objectToBytes(ct, groupObj)

    if debug:
        print("pk => ", pk)
        print("mk => ", mk)
        with open("cipher.txt", "wb") as ctFile:
            ctFile.write(byte_msg)

    return byte_msg
Пример #52
0
 def readParams(filename='pc.param'):
     if (os.path.isfile(filename)):
         group = ECGroup(prime192v1)
         f = open(filename, 'rb')
         params = f.readline()
         f.close()
         params = bytesToObject(params, group)
         return [params, group]
     else:
         raise Exception(
             "I can't find the parameters file. You have to create them first using -n when starting."
         )
    def verify_transaction_signature(self, sender_address,
                                     sender_global_public_key,
                                     recipient_address, value, signature,
                                     transaction):
        """
        Check that the provided signature corresponds to transaction
        signed by the private key (sender_address) or user secret key
        """
        # public_key = RSA.importKey(binascii.unhexlify(sender_address))
        # verifier = PKCS1_v1_5.new(public_key)
        # h = SHA.new(str(transaction).encode('utf8'))
        # return verifier.verify(h, binascii.unhexlify(signature))
        try:
            group = PairingGroup('MNT224')
            shortSig = ShortSig(group)

            sender_public_key = sender_global_public_key
            sender_public_key = sender_public_key.encode()
            sender_public_key = bytesToObject(sender_public_key, group)

            signature = signature.encode()
            signature = bytesToObject(signature, group)

            transaction_json = json.dumps(transaction)
            transaction_hash = SHA256.new(
                data=str(transaction_json).encode('utf-8')).hexdigest()

            transaction_verification = shortSig.verify(sender_public_key,
                                                       transaction_hash,
                                                       signature)
            print('\n\ntransaction_verification : ', transaction_verification)

        except:
            sender_public_key = RSA.importKey(
                binascii.unhexlify(sender_public_key))
            verifier = PKCS1_v1_5.new(sender_public_key)
            h = SHA.new(str(transaction).encode('utf8'))
            return verifier.verify(h, binascii.unhexlify(signature))

        return transaction_verification
    def base64_to_keys(self, data):
        """
        Given a Base64 string, convert it back to a keyring (or similar).

        @return data Base64 string
        @returns Keyring (or similar)

        @throws KeyRingError if no keys are serialized
        """
        keys = bytesToObject(data, self.group)

        # Validate result
        return self.clean_keys(keys)
Пример #55
0
	def __init__(self):
		''' Create the initial master key and then the list to hold the ciphers for encryption.
		'''
		self.groupObj = PairingGroup('SS512')
		if (os.path.isfile('CryptoModule/pubkey.pkl') and os.path.isfile('CryptoModule/masterkey.pkl')):
			print("Loading the master and public key from the file")
			self.public = bytesToObject(pickle.load(open('CryptoModule/pubkey.pkl', 'rb')), self.groupObj)
			self.master = bytesToObject(pickle.load(open('CryptoModule/masterkey.pkl', 'rb')), self.groupObj)
		else:
			self.cpabe = CPabe_BSW07(self.groupObj)
			(self.public, self.master) = self.cpabe.setup()

			# Persist the keys
			outputPublic = open('CryptoModule/pubkey.pkl', 'wb')
			outputMaster = open('CryptoModule/masterkey.pkl', 'wb')
			pickle.dump(objectToBytes(self.public, self.groupObj), outputPublic)
			pickle.dump(objectToBytes(self.master, self.groupObj), outputMaster)
			outputPublic.close()
			outputMaster.close()

		# Cipher list...
		self.cipherList = []
Пример #56
0
def get_vote():
	vote = 2

        group = RSAGroup()
        pai = pkenc_paillier99.Pai99(group)

        f=open('./pyssss/VotingPublic','rb')
        data = f.read()
        public_key = bytesToObject(data,group)

        vote = pai.encode(public_key['n'],vote)
        ciphervote = pai.encrypt(public_key,vote)
        print ciphervote['c']
	ciphertext= specialInt.serialize(ciphervote['c'])
	print ciphertext	
#	ciphervote['c'] = Conversion.bytes2integer(Conversion.IP2OS(7092577248503691820499926901328776752053429606540181306976))

        f=open('./pyssss/VotingPrivate','rb')
        data = f.read()
        secret_key = bytesToObject(data,group)
	ciphertext = specialInt.deserialize(ciphertext)
        #plaintext=pai.decrypt(public_key, secret_key,ciphervote)
	n, n2 = public_key['n'], public_key['n2']
       	plaintext = ((pai.L(ciphertext ** secret_key['lamda'],n) % n) * secret_key['u']) %n 

	print plaintext










        ciphervote=42
        return ciphervote
    def decrypt(self, cipher, secret_keys):
        """
        Decrypt a given cipher message including header. Message category will
        be deduced from cipher.

        @param cipher Message to decrypt
        @param secret_keys Dictionary of secret keys per category
        @return Decrypted message

        @throws DecryptError if data is invalid or if attributes are missing in
            keypairs
        @throws KeyRingError if no public key is available for cipher's category
        """

        # Validate parameters
        secret_keys = self.clean_keys(secret_keys)

        # Create result buffer
        cipher = io.BytesIO(base64.b64decode(cipher))

        # Initialize AES
        try:
            aes_iv = cipher.read(AES.block_size)
            aes_key_size = struct.unpack("<Q", cipher.read(struct.calcsize("Q")))[0]
            aes_key_bytes = cipher.read(aes_key_size)
            aes_key_cipher = bytesToObject(aes_key_bytes, self.group)
        except (TypeError, struct.error, zlib.error) as e:
            raise DecryptError("Decoding cipher failed")

        # Unpack category from cipher
        category = self.clean_category(aes_key_cipher["category"])

        # Unpack key
        try:
            sk = secret_keys[category]
        except LookupError:
            raise KeyRingError("No public key and secret key available for category %s" % category)

        # Decrypt the AES key
        try:
            # For some reason, the decrypt method wants a public key. We don't
            # supply it since it isn't required.
            aes_key_plain = self.scheme.decrypt(None, sk, aes_key_cipher)
        except Exception, e:
            # There is a bug in Charm which requires a fix in the scheme to not
            # crash during execution. See for the idea: http://bit.ly/1e19H7A
            if e.args[0] == "Insufficient attributes":
                raise DecryptError("Missing attributes for decryption")
            else:
                raise e
Пример #58
0
 def on_message(self, client, userdata, msg):
     CT = None
     try:
         groupObj = PairingGroup('SS512')
         CT = bytesToObject(msg.payload, groupObj)
     except:
         print(msg.topic+": "+ msg.payload.decode("utf-8") + " with QoS: " + str(msg.qos))
     
     if self.dek is not None and CT is not None:
         m = self.decAes(CT)
         if msg is None:
             print(msg.topic+": (dec failed!), with QoS: " + str(msg.qos))
         else:
             print(msg.topic+": (dec) "+ m.decode('utf-8') + " with QoS: " + str(msg.qos))
def get_vote():
        vote = raw_input("Enter your vote: ")   #get vote from user
	vote = long(vote)


	group = RSAGroup()
	pai = pkenc_paillier99.Pai99(group)	

	f=open('./pyssss/VotingPublic','rb')
	data = f.read()
	public_key = bytesToObject(data,group)
	
	vote = pai.encode(public_key['n'],vote)
	ciphervote = pai.encrypt(public_key,vote)
	print ciphervote['c']	


	f=open('./pyssss/VotingPrivate','rb')
	data = f.read()
	secret_key = bytesToObject(data,group)

	plaintext=pai.decrypt(public_key, secret_key,ciphervote)
	print plaintext











	ciphervote=42	
        return ciphervote
Пример #60
0
def handleNewConnection():
    sockfd, addr = server_socket.accept()
    userdata[sockfd] = 'Anonymous {}'.format(len(userdata))
    #send the room policy
    sockfd.send(roomPolicy)                                                     
    #send pk and group
    sockfd.send(objectToBytes(pk,groupObj))                                    
    #send key using a attr set
    sockfd.send(objectToBytes(cpabe.keygen(pk, msk, attr_dict[i]),groupObj))    
    #receive the encapsulation
    encap = bytesToObject(sockfd.recv(RECV_BUFFER), groupObj)                   
    #save it
    encapsulations.append(encap)                                                         
    entities.append(addr)
    broadcastEncapList(sockfd, addr) 
    broadcast(sockfd, "[server] {} entered room\n".format(userdata[sockfd]))
    print 'Users in the room: {}\n\n'.format(str(userdata.values()))