Exemplo n.º 1
0
def main():
	global benchmarkResult, options

	options=parse_args()

	rsa=RSA_Sig()
	group=IntegerGroup()
	group.paramgen(1024)

	# initialize key server and user objects
	ks = KS (rsa)
	user = User (group)

	# set up key server
	pk=ks.setup()

	if options.output_file is not None:
		rf=open(options.output_file, "w")
	else:
		rf=sys.stdout
	rf.write ("#KB\tN.KS\tN.kss\tD1\tD2\tHash\tKS\tSE\tTag\tTo.\n")

	for fsize in file_size:
		# generate sample file
		create_file (sample_file, fsize)

		benchmarkResult={}
		for count in range (0,options.trials, 1):
			# compute a hash for a file
			h=user.computeHash(sample_file)

			# generate a key by interacting with KS
			user.generate_key (pk, h, ks)

			# encrypt a file
			user.encrypt (sample_file)

			# compute a tag for the encrypted file
			user.computeTag(sample_file)

		delay_Hash=round(benchmarkResult['Hash']*1000/options.trials,2)
		delay_Tag=round(benchmarkResult['Tag']*1000/options.trials,2)
		delay_SE=round(benchmarkResult['SE']*1000/options.trials,2)
		delay_KS=round(benchmarkResult['KS']*1000/options.trials,2)
		delay_total=round(delay_Hash+delay_Tag+delay_SE+delay_KS,2)

		rf.write("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}\n".format(\
			int(fsize/1024), options.num_of_KS, options.num_of_kss, options.KS_delay1, options.KS_delay2,\
			delay_Hash, delay_KS, delay_SE, delay_Tag,delay_total))
			
	rf.close()
Exemplo n.º 2
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())
Exemplo n.º 3
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
Exemplo n.º 4
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)
Exemplo n.º 5
0
def asym_encrypt(plaintext, public_key):
    encrypter = RSA_Enc()
    serial_pt = objectToBytes(plaintext, IntegerGroup())
    frag_counter = (len(serial_pt) // RKEY_SIZE_BYTES) + 1
    ct_list = []
    for i in range(frag_counter):
        ciphertext = encrypter.encrypt(
            public_key,
            serial_pt[(i * RKEY_SIZE_BYTES):((i + 1) * RKEY_SIZE_BYTES)])
        ct_list.append(ciphertext)
    #end for
    return ct_list
Exemplo n.º 6
0
    def testCS98(self):
        p = integer(
            156053402631691285300957066846581395905893621007563090607988086498527791650834395958624527746916581251903190331297268907675919283232442999706619659475326192111220545726433895802392432934926242553363253333261282122117343404703514696108330984423475697798156574052962658373571332699002716083130212467463571362679
        )
        q = integer(
            78026701315845642650478533423290697952946810503781545303994043249263895825417197979312263873458290625951595165648634453837959641616221499853309829737663096055610272863216947901196216467463121276681626666630641061058671702351757348054165492211737848899078287026481329186785666349501358041565106233731785681339
        )
        groupObj = IntegerGroup()
        pkenc = CS98(groupObj, p, q)

        (pk, sk) = pkenc.keygen(1024)
        M = b"hello world. test message"
        ciphertext = pkenc.encrypt(pk, M)

        message = pkenc.decrypt(pk, sk, ciphertext)

        assert M == message, "UNSUCCESSFUL!!!! :-( why?"
        if debug: print("SUCCESSFULLY RECOVERED => %s" % message)
Exemplo n.º 7
0
def gen_token(sk, I_star):
    """ Create search token for a given query I_star.
    Elements of I_star is 0, 1, or a `WILDCARD`.

    :param sk: secret key
    :param I_star: query
    :returns: search token
    """
    intGroup = IntegerGroup()

    u = sk['u']
    h = sk['h']
    w = sk['w']
    v = sk['v']
    g = sk['g']
    a = sk['a']
    p = sk['p']

    K_0 = g**a
    r_1 = {}
    r_2 = {}
    for i in range(len(I_star)):
        r_1[i] = int(random_zr(intGroup, p))
        r_2[i] = int(random_zr(intGroup, p))

    for i in range(len(I_star)):
        if I_star[i] != 0 and I_star[i] != 1:
            continue
        tmp = u[i]**I_star[i]
        tmp = tmp * h[i]
        tmp = tmp**r_1[i]
        tmp = tmp * (w[i]**r_2[i])
        K_0 = K_0 * tmp

    K_1 = {}
    K_2 = {}
    for i in range(len(I_star)):
        K_1[i] = v**r_1[i]
        K_2[i] = v**r_2[i]

    token = {'I_star': I_star, 'K_0': K_0, 'K_1': K_1, 'K_2': K_2}

    return token
Exemplo n.º 8
0
def encrypt(pk, I, M=None):
    """ Encrypt a index vector I with values of components as 0 or 1, with optional message M

    The message is an element in GT. If it is not provided, the identity element of GT is used

    :param pk: public key
    :param I: a index vector
    :param M: message
    :returns: cipher text for I (and M if any)
    """
    int_group = IntegerGroup()
    g_q = pk['g_q']
    group = pk['group']
    n = group.order()
    s = int(random_zr(int_group, n))
    if M is None:
        M = get_unit_element(group, GT)
    C_prime = (pk['A']**s) * M

    Z = g_q**int(random_zr(int_group, n))
    C_0 = (pk['V']**s) * Z

    C_1 = {}
    C_2 = {}
    U = pk['U']
    H = pk['H']
    W = pk['W']
    for i in range(len(I)):
        Z_1_i = g_q**int(random_zr(int_group, n))
        C_1[i] = (((U[i]**I[i]) * H[i])**s) * Z_1_i

        Z_2_i = g_q**int(random_zr(int_group, n))
        C_2[i] = (W[i]**s) * Z_2_i

    C = {'C_prime': C_prime, 'C_0': C_0, 'C_1': C_1, 'C_2': C_2}

    return C
Exemplo n.º 9
0
import sys
import json
from pre_mg07b import PreGA
from charm.toolbox.pairinggroup import PairingGroup
from charm.toolbox.integergroup import IntegerGroup
from charm.core.engine.util import objectToBytes, bytesToObject

IDFrom = sys.argv[1]
IDTo = sys.argv[2]
group = PairingGroup('SS512', secparam=1024)
ibp = PreGA(group)
f = open('./setup/master.param', 'r')
bin_data = f.read()
params = bytesToObject(bin_data, group)
f = open('./userkeys/' + IDFrom + '.key', 'r')
bin_data = f.read()
id_secret_key = bytesToObject(bin_data, group)
f.close()
f = open('./setup/master.param', 'r')
bin_data = f.read()
params = bytesToObject(bin_data, group)
f.close()
re_encryption_key = ibp.rkGen(params, id_secret_key, IDFrom, IDTo)
rk_json = {
    'N': objectToBytes(re_encryption_key['N'], IntegerGroup()),
    'R': objectToBytes(re_encryption_key['R'], group),
}
f = open('./re-keys/' + IDFrom + "" + IDTo + '.key', 'w')
f.write(json.dumps(rk_json))
f.close()
Exemplo n.º 10
0
IDFrom = sys.argv[1]
IDTo = sys.argv[2]
file_name = sys.argv[3]
'''Group set up'''
group = PairingGroup('SS512', secparam=1024)
ibp = PreGA(group)
f = open('./setup/master.param', 'r')
bin_data = f.read()
params = bytesToObject(bin_data, group)
f.close()
''' End set up'''
''' Load re-encryption key '''
f = open('./re-keys/' + IDFrom + "" + IDTo + '.key', 'r')
bin_data = f.readline()
rk_json = json.loads(bin_data)
N = bytesToObject(rk_json['N'], IntegerGroup())
R = bytesToObject(rk_json['R'], group)
re_encryption_key = {'N': N, 'R': R}
f.close()
''' End lre-encryption key '''
''' Load ciphertexts '''
f = open('./ciphertexts/' + IDFrom + file_name + '.enc', 'r')
bin_data = f.readline()
ct = json.loads(bin_data)
A = bytesToObject(ct['CA'], group)
B = bytesToObject(ct['CB'], group)
C = bytesToObject(ct['CC'], IntegerGroup())
S = bytesToObject(ct['S'], group)
C_ = {'A': A, 'B': B, 'C': C}
encr_key = {'S': S, 'C': C_}
f.close()
Exemplo n.º 11
0
bin_data = f.read()
params = bytesToObject(bin_data, group)
''' End set up'''
''' Load user key'''
f = open('./userkeys/' + ID + '.key', 'r')
bin_data = f.read()
id_secret_key = bytesToObject(bin_data, group)
f.close()
''' End loading user key '''
''' Load ciphertexts '''
f = open('./ciphertexts/' + ID + file_name + '.enc', 'r')
bin_data = f.readline()
ct = json.loads(bin_data)
A = bytesToObject(ct['CA'], group)
B = bytesToObject(ct['CB'], group)
C = bytesToObject(ct['CC'], IntegerGroup())
S = bytesToObject(ct['S'], group)
C_ = {'A': A, 'B': B, 'C': C}
encr_key = {'S': S, 'C': C_}
ciphertext = ct['Data']
f.close()
''' End loading ciphertexts '''
'''Symmetric encryption key and algorithm set up'''
sym_key = ibp.decryptFirstLevel(params, id_secret_key, encr_key, ID)
sym_cipher = AuthenticatedCryptoAbstraction(sym_key)
'''End set up'''
''' File decyption process '''
file_decrypted = sym_cipher.decrypt(ciphertext)
f = open('./plaintexts/' + file_name, 'w')
f.write(file_decrypted)
f.close()
Exemplo n.º 12
0
def random_zr(group: IntegerGroup, r):
    """ Generate a random element in Zr
    """
    return group.random(max=int(r))
Exemplo n.º 13
0
def setup(width: int, group_param: dict):
    """
    Performs the setup algorithm for HVE.

    The group params should:
    - 'type': 'a1'
    - contain values for 'p', 'n', 'l'
    - contain 2 primes 'n0', 'n1' where n = n0 * n1

    :param int width: the length of attribute vector
    :param dict group_param: group parameters

    :returns: (publicKey, secretKey) pair
    """
    int_group = IntegerGroup()

    p = group_param[PARAM_KEY_N0]
    q = group_param[PARAM_KEY_N1]

    group_param_copy = group_param.copy(
    )  # remove private components of the group parameters
    group_param_copy.pop(PARAM_KEY_N0, None)
    group_param_copy.pop(PARAM_KEY_N1, None)

    group = PairingGroup()
    group.init_from_str(convert_params_to_string(group_param_copy))

    g_q = random_gq(group, p, q)
    a = int(random_zr(int_group, p))

    u = {}
    h = {}
    w = {}
    for i in range(width):
        u[i] = random_gp(group, p, q)
        h[i] = random_gp(group, p, q)
        w[i] = random_gp(group, p, q)

    g = random_gp(group, p, q)
    v = random_gp(group, p, q)
    assert g.initPP(), "ERROR: Failed to init pre-computation table for g."
    assert v.initPP(), "ERROR: Failed to init pre-computation table for v."

    V = v * random_gq(group, p, q)
    A = pair(g, v)**a
    U = {}
    H = {}
    W = {}
    for i in range(width):
        U[i] = u[i] * random_gq(group, p, q)
        H[i] = h[i] * random_gq(group, p, q)
        W[i] = w[i] * random_gq(group, p, q)

    pk = {'group': group, 'g_q': g_q, 'V': V, 'A': A, 'U': U, 'H': H, 'W': W}

    sk = {
        'group': group,
        'g_q': g_q,
        'a': a,
        'u': u,
        'h': h,
        'w': w,
        'g': g,
        'v': v,
        'p': p,
        'q': q
    }

    return (pk, sk)
Exemplo n.º 14
0
        if sk is None:
            sk = [random.randint(0, 1) for _ in range(self.n)]
        pk = [self.g**t for t in self.k]
        h  = reduce(lambda a, b: a * b, [g**s for g, s in zip(pk, sk)])**(-1)
        pk += [h]

        return {"public_key": pk, "secret_key": sk}

    def encrypt(self, pk, m):
        return [g**self.r for g in pk[0:-1]] + [m * pk[-1]**self.r]

    def decrypt(self, sk, c):
        return c[-1] * reduce(lambda a, b: a * b, [g**s for g, s in zip(c[0:-1], sk)])


if __name__ == '__main__':
    from charm.toolbox.integergroup import IntegerGroup
    groupObj = IntegerGroup()
    groupObj.paramgen(1024)
    r = groupObj.random()

    k  = [groupObj.random() for _ in range(4)]
    g1 = groupObj.randomGen()

    bhho = BHHO(groupObj, g1, k, r)
    keys = bhho.generate_key()
    m1 = groupObj.random()
    c = bhho.encrypt(keys["public_key"], m1)
    m2 = bhho.decrypt(keys["secret_key"], c)
    print(m1==m2)
Exemplo n.º 15
0
def benchmark_hve_sigle_operation():
    """
    """
    group_params = dict()
    group_params[256] = parse_params_from_string(
        pairingcurves.PAIRING_CURVE_TYPE_A1_256_SAMPLE)
    group_params[512] = parse_params_from_string(
        pairingcurves.PAIRING_CURVE_TYPE_A1_512_SAMPLE)
    group_params[1024] = parse_params_from_string(
        pairingcurves.PAIRING_CURVE_TYPE_A1_1024_SAMPLE)
    group_params[2048] = parse_params_from_string(
        pairingcurves.PAIRING_CURVE_TYPE_A1_2048_SAMPLE)

    num_runs = 10
    headers = [
        'bitLen', 'time_random_element', 'time_power_g',
        'time_random_element_subgroup', 'time_random_element_zr', 'time_pair',
        'time_power_gt', 'time_mul_two_subgroup', 'time_div_gt'
    ]
    with open('benchmark_operation.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(headers)
        for bitLen, groupParam in group_params.items():
            print('--------------------------------------------')
            print('bitLen=', bitLen)
            int_group = IntegerGroup()

            p = int(groupParam[hvehelper.PARAM_KEY_N0])
            q = int(groupParam[hvehelper.PARAM_KEY_N1])

            group = pairinggroup.PairingGroup()
            group.init_from_str(
                pairinggroup.convert_params_to_string(groupParam))

            start_time = time.time()
            for _ in range(num_runs):
                tmp = group.random(pairinggroup.G1)
            end_time = time.time()
            time_random_element = (end_time - start_time) / num_runs
            print('time_random_element=', time_random_element)
            tmp = group.random(pairinggroup.G1)
            print('base_1:', tmp)

            start_time = time.time()
            for i in range(num_runs):
                _ = tmp**p
            end_time = time.time()
            time_power_g = (end_time - start_time) / num_runs
            print('time_power_g=', time_power_g)
            time_random_element_subgroup = time_random_element + time_power_g
            print('time_random_element_subgroup=',
                  time_random_element_subgroup)

            start_time = time.time()
            for _ in range(num_runs):
                a = int_group.random(max=int(p))
            end_time = time.time()
            time_random_element_zr = (end_time - start_time) / num_runs
            print('time_random_element_zr=', time_random_element_zr)
            a = int(hve.random_zr(int_group, p))

            g = hve.random_gp(group, p, q)
            v = hve.random_gp(group, p, q)

            start_time = time.time()
            for _ in range(num_runs):
                tmp = hve.pair(g, v)
            end_time = time.time()
            time_pair = (end_time - start_time) / num_runs
            print('time_pair=', time_pair)
            A = hve.pair(g, v)
            print('base_2:', A)

            start_time = time.time()
            for _ in range(num_runs):
                tmp = A**p
            end_time = time.time()
            time_power_gt = (end_time - start_time) / num_runs
            print('time_power_gt=', time_power_gt)

            tmp = hve.random_gq(group, p, q)
            start_time = time.time()
            for _ in range(num_runs):
                v * tmp
            end_time = time.time()
            time_mul_two_subgroup = (end_time - start_time) / num_runs
            print('time_mul_two_subgroup=', time_mul_two_subgroup)

            g = hve.random_gp(group, p, q)
            v = hve.random_gp(group, p, q)
            t1 = hve.pair(g, v)
            g = hve.random_gp(group, p, q)
            v = hve.random_gp(group, p, q)
            t2 = hve.pair(g, v)

            start_time = time.time()
            for _ in range(num_runs):
                t1 / t2
            end_time = time.time()
            time_div_gt = (end_time - start_time) / num_runs
            print('time_div_gt=', time_div_gt)

            writer.writerow([
                bitLen, time_random_element, time_power_g,
                time_random_element_subgroup, time_random_element_zr,
                time_pair, time_power_gt, time_mul_two_subgroup, time_div_gt
            ])
# -*- coding: utf-8 -*-
from charm.toolbox.integergroup import IntegerGroup
from charm.toolbox.securerandom import OpenSSLRand
from GarbledCircuit.garbled_circuit import *
from GarbledCircuit.commitment import Commitment
from GarbledCircuit.PRNG import PRNG
import sys
import operator as op
from functools import reduce


if __name__ == '__main__':
    # init game
    group = IntegerGroup()
    group.paramgen(1024)

    f = (4, 1, 3, {5: 1, 6: 3, 7: 5}, {5: 2, 6: 4, 7: 6}, [op.and_, op.xor, op.or_])

    gc = GarbledCircuit()
    C = Commitment(group)
    pk, sk = C.get_key()

    ssl = OpenSSLRand()

    p1 = dict()
    p2 = dict()
    p3 = dict()

    # Step 1
    p1["x1"]  = int.from_bytes(ssl.getRandomBits(1), sys.byteorder)
    p2["x2"]  = int.from_bytes(ssl.getRandomBits(1), sys.byteorder)
Exemplo n.º 17
0
from MYPRF import MYPRF

from length_functions import *

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect to party B
server_address = ('localhost', 10000)



# long-term key generation, session execution, then session key output

# length of group elements, may change this later
# generate the group G
bits = 1024
group = IntegerGroup()
group.paramgen(bits)
group_order = group.q
#print('group order is ', group_order)
print('group.p = ', group.p)
print('group.q = ', group.q)

group_p_bytes = Conversion.IP2OS(group.p, 128)
group_q_bytes = Conversion.IP2OS(group.q, 128)


alpha_1_value = randomBits(160) % group_order
alpha_2_value = randomBits(160) % group_order
beta_1_value = randomBits(160) % group_order
beta_2_value = randomBits(160) % group_order
alpha_1_bytes = Conversion.IP2OS(alpha_1_value, 20)
Exemplo n.º 18
0
'''Group set up'''
group = PairingGroup('SS512', secparam=1024)
ibp = PreGA(group)
f = open('./setup/master.param', 'r')
bin_data = f.read()
params = bytesToObject(bin_data, group)
f.close()
''' End set up'''
'''Symmetric encryption key and algorithm set up'''
sym_key = OpenSSLRand().getRandomBytes(16)
sym_cipher = AuthenticatedCryptoAbstraction(sym_key)
'''End set up'''
'''Encryption proccess'''
sym_key_ciphertext = ibp.encrypt(params, ID, sym_key)
# encrypt the symmetric encryption key
f = open(file_name, 'r')
file_data = f.read()
file_ciphertext = sym_cipher.encrypt(file_data)
'''End of encryption process'''

ct = {
    'CA': objectToBytes(sym_key_ciphertext['C']['A'], group),
    'CB': objectToBytes(sym_key_ciphertext['C']['B'], group),
    'CC': objectToBytes(sym_key_ciphertext['C']['C'], IntegerGroup()),
    'S': objectToBytes(sym_key_ciphertext['S'], group),
    'Data': file_ciphertext
}
f = open('./ciphertexts/' + ID + file_name + '.enc', 'w')
f.write(json.dumps(ct))
f.close()
Exemplo n.º 19
0
def sign(data, private_key):
    signer = RSA_Sig()
    sig = signer.sign(private_key[1], data)
    sig = Conversion.OS2IP(sig)
    serial_data_and_sig = objectToBytes([data, sig], IntegerGroup())
    return serial_data_and_sig