Best Python code snippet using localstack_python
re_enc_primitives1.py
Source:re_enc_primitives1.py  
...11from const import SEED_LENGTH, SYM_KEY_DEFAULT_SIZE12from sym_enc_primitives import sym_decrypt, sym_encrypt13import logging14import random   # [WARNING] NOT CRYPTOGRAPHICALLY SECURE15def re_encrypt(data=None, args=None, debug=0):16    """ TODO AGGIORNARE DOCUMENTAZIONE E CONTROLLI VARIABILI17    Re-encrypt the ciphertext using the punctured encryption with new keys.18    :param ciphertext_infile: input file for re-encryption19    :param re_enc_length: number of bytes to re-encrypt20    :param new_pk_file: file where the new public key is stored21    :param policy: string containing the policy to apply to seed and key during encryption22    :param debug: if 1, prints will be shown during execution; default 0, no prints are shown23    :return: the new ciphertext with all the parameters required for decryption24    """25    # Check if data is set26    if data is None:27        logging.error('re_encrypt ciphertext_infile exception')28        if debug:  # ONLY USE FOR DEBUG29            print('EXCEPTION in re_encrypt ciphertext_infile')...securesstable.py
Source:securesstable.py  
...39        for i in range(1, n):40            D_i = c1 - c2 - public_key.encrypt(i)41            D.append(D_i)4243        D = [re_encrypt(i) for i in D]44        sigma = np.random.permutation(len(D))45        D = [D[i] for i in sigma]46        for i in range(len(D)):47            if EQ_TEST(D[i], public_key.encrypt(0), private_key) == 1:48                return True4950        return False5152    def re_encrypt(c1):53        temp = public_key.encrypt(0)54        temp = c1 + temp55        return temp5657    def add_1(c1):58        temp = public_key.encrypt(1)59        temp = c1 + temp60        return temp61    ##### INPUT SUBMISSION ############6263    # def gen_prefs(n):64    #     l = np.empty([n, n]).astype(int).tolist()65    #     for i in range(n):66    #         pi = np.random.permutation(n).astype(int).tolist()67    #         l[i] = [x for x in pi]68    #     return l6970    # men_preferences = gen_prefs(n)71    # women_preferences = gen_prefs(n)72    # print(men_preferences)73    # print(women_preferences)7475    def gen_enc(n, preferences):76        men = dict()77        for i in range(n):78            men[i] = [public_key.encrypt(x) for x in preferences[i]]79        return men8081    men = gen_enc(n, men_preferences)82    women = gen_enc(n, women_preferences)8384    # ##### INPUT SUBMISSION ############8586    # #### ADDITION OF FAKE MEN ########87    # # The matching authorities define an additional n fake men88    for i in range(n, 2*n):89        pi = np.random.permutation(n).tolist()90        men[i] = [public_key.encrypt(x) for x in pi]9192    # # augmented preferences for woman is (i-1) for i in (n+1,2n)93    augment = list(range(n, 2*n))94    augment_ranklist = [public_key.encrypt(x) for x in augment]95    for i in range(0, n):96        women[i].extend(augment_ranklist)9798    # #### ADDITION OF FAKE MEN ########99100    # ######## BID CREATION #########101    bids = dict()102103    def create_bids():104        a = list(range(1, n+1))105106        for i in range(2*n):107            women_pref = []108            for j in range(n):109                women_pref.append(women[j][i])110111            bids[i] = np.array([public_key.encrypt(i+1), np.array(men[i]), np.array([public_key.encrypt(x)112                                                                                     for x in a]), np.array(women_pref), public_key.encrypt(0)])  # each element of dict is a nparray113114    create_bids()115    Free_bids, Engaged_bids = [], []116    for i in range(n):117        Free_bids.append(bids[i])118        Engaged_bids.append(119            np.array([bids[i+n], public_key.encrypt(i+1), women[i][i+n]]))120121    Free_bids = np.array(Free_bids)122    Engaged_bids = np.array(Engaged_bids)123124    # ######## BID CREATION #########125126    ###### Initial Mixing #########127    pi = np.random.permutation(n)128129    def pi_per(ciphers):130        ciphers = np.apply_along_axis(lambda x: re_encrypt(x), 0, ciphers)131        ciphers = ciphers[pi]132        return ciphers133134    def External_Mix_Free(bids):135        if len(bids) == 0:136            return bids137138        for i in range(len(bids)):139            bids[i] = np.array([re_encrypt(bids[i][0]), np.array(np.apply_along_axis(lambda x: re_encrypt(x), 0, bids[i][1])), np.array(140                np.apply_along_axis(lambda x: re_encrypt(x), 0, bids[i][2])), np.array(np.apply_along_axis(lambda x: re_encrypt(x), 0, bids[i][3])), re_encrypt(bids[i][4])])141142        sigma = np.random.permutation(len(bids))143        bids = bids[sigma]144        return bids145146    def Internal_Mix_Free(bids):147        if len(bids) == 0:148            return bids149150        for i in range(len(bids)):151            bids[i] = np.array([bids[i][0], pi_per(bids[i][1]), pi_per(152                bids[i][2]), pi_per(bids[i][3]), bids[i][4]])153        return bids154155    def External_Mix_Engaged(bids):156        if len(bids) == 0:157            return bids158159        for i in range(len(bids)):160            bids[i] = np.array([np.array([re_encrypt(bids[i][0][0]), np.array(np.apply_along_axis(lambda x: re_encrypt(x), 0, bids[i][0][1])), np.array(np.apply_along_axis(161                lambda x: re_encrypt(x), 0, bids[i][0][2])), np.array(np.apply_along_axis(lambda x: re_encrypt(x), 0, bids[i][0][3])), re_encrypt(bids[i][0][4])]), re_encrypt(bids[i][1]), re_encrypt(bids[i][2])])162163        sigma = np.random.permutation(len(bids))164        bids = bids[sigma]165        return bids166167    def Internal_Mix_Engaged(bids):168        if len(bids) == 0:169            return bids170171        for i in range(len(bids)):172            bids[i] = np.array([np.array([bids[i][0][0], pi_per(bids[i][0][1]), pi_per(173                bids[i][0][2]), pi_per(bids[i][0][3]), bids[i][0][4]]), bids[i][1], bids[i][2]])174        return bids175176    ###### Initial Mixing #########177    Free_bids = External_Mix_Free(Free_bids)178    Engaged_bids = External_Mix_Engaged(Engaged_bids)179    Free_bids = Internal_Mix_Free(Free_bids)180    Engaged_bids = Internal_Mix_Engaged(Engaged_bids)181182    FREE_BIDS = {1: Free_bids}183    ENGAGED_BIDS = {1: Engaged_bids}184185    ######### Computing a stable match ###########186    for i in range(2, n+2):187        FREE_BIDS[i] = None188        ENGAGED_BIDS[i] = None189    ###########################190191    for k in range(1, n+1):192        while len(FREE_BIDS[k]) > 0:193            ind = random.randrange(0, len(FREE_BIDS[k]))194            bid = FREE_BIDS[k][ind]195            FREE_BIDS[k] = np.delete(FREE_BIDS[k], ind, 0)196197            index = INDEX(bid[1], bid[4], private_key)198            E_j = bid[2][index]199            E_sji = bid[3][index]200201            for i in range(len(ENGAGED_BIDS[k])):202                if EQ_TEST(E_j, ENGAGED_BIDS[k][i][1], private_key) == 1:203                    conflict_bid = ENGAGED_BIDS[k][i]204                    ENGAGED_BIDS[k] = np.delete(ENGAGED_BIDS[k], i, 0)205                    break206207            new_engaged_bid = np.array([np.array(bid), E_j, E_sji])208209            temp_Engaged_bids = np.array([new_engaged_bid, conflict_bid])210            # temp_Engaged_bids=External_Mix_Engaged(temp_Engaged_bids)211            result = COMPARE(212                temp_Engaged_bids[0][2], temp_Engaged_bids[1][2], private_key, 2*n)213214            if not result:215216                ENGAGED_BIDS[k] = np.append(217                    ENGAGED_BIDS[k], [temp_Engaged_bids[0]], axis=0)218219                w1 = temp_Engaged_bids[1][0]220                w1[4] = add_1(w1[4])221222                if FREE_BIDS[k+1] is None:223                    FREE_BIDS[k+1] = np.array([w1])224                else:225                    FREE_BIDS[k+1] = np.append(FREE_BIDS[k+1], [w1], axis=0)226227            else:228229                ENGAGED_BIDS[k] = np.append(230                    ENGAGED_BIDS[k], [temp_Engaged_bids[1]], axis=0)231                w1 = temp_Engaged_bids[0][0]232                w1[4] = add_1(w1[4])233                if FREE_BIDS[k+1] is None:234                    FREE_BIDS[k+1] = np.array([w1])235236                else:237                    FREE_BIDS[k+1] = np.append(FREE_BIDS[k+1], [w1], axis=0)238            ####################239240            ENGAGED_BIDS[k] = External_Mix_Engaged(ENGAGED_BIDS[k])241            ENGAGED_BIDS[k] = Internal_Mix_Engaged(ENGAGED_BIDS[k])242            FREE_BIDS[k] = Internal_Mix_Free(FREE_BIDS[k])243            FREE_BIDS[k+1] = Internal_Mix_Free(FREE_BIDS[k+1])244245        ENGAGED_BIDS[k+1] = ENGAGED_BIDS[k]246247        FREE_BIDS[k+1] = External_Mix_Free(FREE_BIDS[k+1])248        ENGAGED_BIDS[k+1] = External_Mix_Engaged(ENGAGED_BIDS[k+1])249        FREE_BIDS[k+1] = Internal_Mix_Free(FREE_BIDS[k+1])250        ENGAGED_BIDS[k+1] = Internal_Mix_Engaged(ENGAGED_BIDS[k+1])251252    ######### Computing a stable match ###########253254    ############# Decryption ###########255    pairs = []256    for bid in ENGAGED_BIDS[n+1]:257        pairs.append([bid[0][0], bid[1]])258259    for pair in pairs:260        pair = [re_encrypt(pair[0]), re_encrypt(pair[1])]261    sigma = np.random.permutation(len(pairs))262    pairs = [pairs[i] for i in sigma]263264    #########Decryption ################265    for i in range(len(pairs)):266        pairs[i] = [private_key.decrypt(267            pairs[i][0]), private_key.decrypt(pairs[i][1])]268    return pairs269# print(pairs)270st.set_page_config(layout="centered") 271st.title('Secure Stable Matching ')272n = st.slider('Enter the number the participants', 0, 50, 1)273st.write('Number of participants chosen: ',n)274
...pre_nal16.py
Source:pre_nal16.py  
...26    >>> (pk_b, sk_b) = pre.keygen(params)27    >>> msg = groupObj.random(GT)28    >>> c_a = pre.encrypt(params, pk_a, msg)29    >>> rk = pre.rekeygen(params, pk_a, sk_a, pk_b, sk_b)30    >>> c_b = pre.re_encrypt(params, rk, c_a)31    >>> assert msg == pre.decrypt(params, sk_b, c_b), 'Decryption of re-encrypted ciphertext was incorrect'32    """33    34    def __init__(self, groupObj):35        global group36        group = groupObj37        38    def F(self, params, t):39        return (params['u'] ** t) * params['v']40    def setup(self):41        g, u, v = group.random(G1), group.random(G1), group.random(G1)42        Z = pair(g,g)43        params = {'g': g, 'u': u, 'v': v, 'Z': Z} 44        if(debug):45            print("Setup: Public parameters...")46            group.debug(params)47        return params48    def keygen(self, params):49        x = group.random(ZR)50        g_x = params['g'] ** x51        sk = x      # { 'sk' : x }52        pk = g_x    # { 'pk' : g_x }53        if(debug):54            print('\nKeygen...')55            print("pk => '%s'" % pk)56            print("sk => '%s'" % sk)57        return (pk, sk)58    def rekeygen(self, params, pk_a, sk_a, pk_b, sk_b):59        rk = pk_b ** (~sk_a)60        if(debug):61            print('\nReKeyGen...')62            print("rk => '%s'" % rk)63        return rk64    def encrypt(self, params, pk, m):65        #m = group.encode(M, GT)66        r1, r2 = group.random(ZR), group.random(ZR)67        68        c0 = self.F(params, r1) ** r269        c1 = m * (params['Z'] ** r2)70        c2 = pk ** r271        c = {'c0': c0, 'c1': c1, 'c2': c2}72               73        if(debug):74            print('\nEncrypt...')75            print('m => %s' % m)76            print('r1 => %s' % r1)77            print('r2 => %s' % r2)78            print('c => %s' % c)79            group.debug(c)80        return c  81        82    def decrypt(self, params, sk, c):83    84        c1 = c['c1'] 85        c2 = c['c2']86        m = c1 / (c2 ** (~sk))87        88        if(debug):89            print('\nDecrypt...')90            print('m => %s' % m)91        #return group.decode(m)92        return m93        94    def re_encrypt(self, params, rk, c_a):95        c2 = c_a['c2']96        c_b = c_a97        c_b['c2'] = pair(c2, rk)98        99        if(debug):100            print('\nRe-encrypt...')101            print('c\' => %s' % c_b)102        return c_b103class NAL16b(NAL16a):104    """105    Testing NAL16 implementation 106    >>> from charm.toolbox.pairinggroup import PairingGroup,ZR,G1,G2,GT,pair107    >>> groupObj = PairingGroup('SS512')108    >>> pre = NAL16b(groupObj)109    >>> params = pre.setup()110    >>> (pk_a, sk_a) = pre.keygen(params)111    >>> (pk_b, sk_b) = pre.keygen(params)112    >>> msg = b"Hello world!"113    >>> c_a = pre.encrypt(params, pk_a, msg)114    >>> rk = pre.rekeygen(params, pk_a, sk_a, pk_b, sk_b)115    >>> c_b = pre.re_encrypt(params, rk, c_a)116    >>> assert msg == pre.decrypt(params, sk_b, c_b), 'Decryption of re-encrypted ciphertext was incorrect'117    """118    def __init__(self, groupObj):119        global group, h120        group = groupObj121        h = Hash(group)122    def H(self, gt, s):123        h1 = group.hash((gt, s, 1), ZR)124        h2 = group.hash((gt, s, 2), ZR)125        if(debug):126            print('\nH ...')127            print("gt => '%s'" % gt)128            print("s => '%s'" % s)129            print("h1 => '%s'" % h1)130            print("h2 => '%s'" % h2)131        return (h1, h2)132    def G(self, x):133        hh = h.hashToZn(x)134        if(debug):135            print('\nG ...')136            print("x => '%s'" % x)137            print("G(x) => '%s'" % hh)138        return hh139    def encrypt(self, params, pk, m):140        sigma = group.random(GT)141        c3 = self.G(sigma) ^ integer(m)142        (r1, r2) = self.H(sigma, c3)143        c = super(NAL16b, self).encrypt(params, pk, sigma)144        c['c3'] = c3145               146        if(debug):147            print('\nEncrypt...')148            print('m => %s' % m)149            print('r1 => %s' % r1)150            print('r2 => %s' % r2)151            print('c => %s' % c)152            group.debug(c)153        return c 154    def decrypt(self, params, sk, c):155        sigma = super(NAL16b, self).decrypt(params, sk, c)156        c3 = c['c3']157        (r1, r2) = self.H(sigma, c3)158        m = int2Bytes(c3 ^ self.G(sigma))159        160        if(debug):161            print('\nDecrypt...')162            print('m => %s' % m)163        return m164    def re_encrypt(self, params, rk, c_a):165        c_b = super(NAL16b, self).re_encrypt(params, rk, c_a)166        c_b['c3'] = c_a['c3']167        if(debug):168            print('\nRe-encrypt...')169            print('c\' => %s' % c_b)170        return c_b171# groupObj = PairingGroup('SS512')172# pre = NAL16b(groupObj)173# params = pre.setup()174# (pk_a, sk_a) = pre.keygen(params)175# (pk_b, sk_b) = pre.keygen(params)176# msg = b"Hello world!"177# c_a = pre.encrypt(params, pk_a, msg)178# rk = pre.rekeygen(params, pk_a, sk_a, pk_b, sk_b)179# c_b = pre.re_encrypt(params, rk, c_a)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
