def derive_pwe_ecc(password, addr1, addr2, curve_name="p256"): curve = ECC._curves[curve_name] bits = curve.modulus_bits assert bits % 8 == 0 addr1 = binascii.unhexlify(addr1.replace(':', '')) addr2 = binascii.unhexlify(addr2.replace(':', '')) hash_pw = addr1 + addr2 if addr1 > addr2 else addr2 + addr1 for counter in range(1, 100): hash_data = str2bytes(password) + struct.pack("<B", counter) pwd_seed = HMAC256(hash_pw, hash_data) log(DEBUG, "PWD-seed: %s" % pwd_seed) pwd_value = KDF_Length(pwd_seed, "SAE Hunting and Pecking", curve.p.to_bytes(bits // 8), bits) log(DEBUG, "PWD-value: %s" % pwd_value) pwd_value = int(binascii.hexlify(pwd_value), 16) if pwd_value >= curve.p: continue x = Integer(pwd_value) y_sqr = (x**3 - x * 3 + curve.b) % curve.p if legendre_symbol(y_sqr, curve.p) != 1: continue y = y_sqr.sqrt(curve.p) y_bit = getord(pwd_seed[-1]) & 1 if y & 1 == y_bit: return ECC.EccPoint(x, y, curve_name) else: return ECC.EccPoint(x, curve.p - y, curve_name)
def run_test_scalarmul_deterministic(): pointexp = ECC.EccPoint(xexp, yexp, curve='p256') resref = pointexp * kexp init_dmem() xres, yres = run_scalarmult(xexp, yexp, kexp) resbn = ECC.EccPoint(xres, yres, curve='p256') if not resref == resbn: raise Exception( 'Wrong result for scalar point multiplication (deterministic)')
def run_test_scalarmul_random(): randkey = ECC.generate(curve='P-256') randx = int(randkey.public_key().pointQ.x.to_bytes(32).hex(), 16) randy = int(randkey.public_key().pointQ.y.to_bytes(32).hex(), 16) randk = int( Integer.random_range( min_inclusive=1, max_exclusive=P256_CURVE_ORDER).to_bytes(32).hex(), 16) randp = ECC.EccPoint(randx, randy, curve='p256') resref = randp * randk init_dmem() xres, yres = run_scalarmult(randx, randy, randk) resbn = ECC.EccPoint(xres, yres, curve='p256') if not resref == resbn: raise Exception( 'Wrong result for scalar point multiplication (random)')
def derive_pwe_ecc_eappwd(password, peer_id, server_id, token, curve_name="p256", info=None): curve = ECC._curves[curve_name] bits = curve.modulus_bits hash_pw = struct.pack(">I", token) + str2bytes(peer_id + server_id + password) for counter in range(1, 100): hash_data = hash_pw + struct.pack("<B", counter) pwd_seed = HMAC256(b"\x00", hash_data) log(DEBUG, "PWD-Seed: %s" % pwd_seed) pwd_value = KDF_Length_eappwd(pwd_seed, "EAP-pwd Hunting And Pecking", bits) log(DEBUG, "PWD-Value: %s" % pwd_value) pwd_value = int(binascii.hexlify(pwd_value), 16) if bits % 8 != 0: pwd_value = pwd_value >> (8 - (521 % 8)) if pwd_value >= curve.p: continue x = Integer(pwd_value) log(DEBUG, "X-candidate: %x" % x) y_sqr = (x**3 - x * 3 + curve.b) % curve.p if legendre_symbol(y_sqr, curve.p) != 1: continue y = y_sqr.sqrt(curve.p) y_bit = getord(pwd_seed[-1]) & 1 if y & 1 == y_bit: if not info is None: info["counter"] = counter return ECC.EccPoint(x, y, curve_name) else: if not info is None: info["counter"] = counter return ECC.EccPoint(x, curve.p - y, curve_name)
def __init__(self, curve_name: str = DEFAULT_CURVE): """ Construct the curve from a given curve name (according to curves present in PyCryptodome). :param curve_name: """ if curve_name not in ECC._curves: raise ThresholdCryptoError('Unsupported curve: ' + curve_name) self._name = curve_name self._curve = ECC._curves[curve_name] self.P = ECC.EccPoint(x=self._curve.Gx, y=self._curve.Gy, curve=curve_name)
def from_json(cls, json_str: str): """ Create object from json representation. Some special cases are already handled here. """ dict = json.loads(json_str) for k, val in dict.items(): # special handling of bytes if isinstance(val, str) and val.startswith(cls.BASE64_MAGIC): dict[k] = base64.b64decode( val[len(cls.BASE64_MAGIC):].encode('ascii')) # special handling of curve parameters if isinstance(val, str) and val.startswith(cls.CURVE_MAGIC): dict[k] = CurveParameters( curve_name=val[len(cls.CURVE_MAGIC):]) # special handling of curve points if _is_serialized_ecc_point(val): dict[k] = ECC.EccPoint(**val) if _is_serialized_ecc_point_list(dict[k]): dict[k] = [ECC.EccPoint(**s_point) for s_point in val] return cls(**dict)
def key_matrix_generator_Bob(public_key,array_of_images): """Key Matrix Generator""" key=ECC.import_key(public_key) #importing private key from Alice Q=key.pointQ P=ECC.EccPoint(x=key._curve.Gx,y=key._curve.Gy, curve='P-256') n=32 k_b = (random.randrange(2**(n-1)+1, 2**n - 1) ) k_c = (random.randrange(2**(n-1)+1, 2**n - 1)) ##note call the proper definition, R=k_b*P S=k_c*P K_0 = k_b*Q L = k_c*Q K_M=key_matrix_generator(K_0,L,array_of_images) # np.savetxt("Matrix.txt",(K_M)) return K_M,R,S
def retrieve_tpki_ui(self, round): filter_tpk = self.contract.events.PublicKey.createFilter( fromBlock=0, argument_filters={"round": round}) events = filter_tpk.get_all_entries() print("number of temporary ids:", len(events)) if len(events) == self.group_size: self.tp_anon_id[round] = [] for event in events: uj = event['args']['anonymous_id'] coord_ecc_point = event['args']['public_key'] tpkj = ECC.EccPoint(coord_ecc_point[0], coord_ecc_point[1]) self.tp_anon_id[round].append({'uj': uj, 'tpkj': tpkj}) self.tp_anon_id[round] = sorted(self.tp_anon_id[round], key=lambda k: k['uj']) return True return False
def send_commit(self, password): self.pwe = derive_pwe_ecc(password, self.dstaddr, self.srcaddr) # After generation of the PWE, each STA shall generate a secret value, rand, and a temporary secret value, # mask, each of which shall be chosen randomly such that 1 < rand < r and 1 < mask < r and (rand + mask) # mod r is greater than 1, where r is the (prime) order of the group. self.rand = random.randint(0, secp256r1_r - 1) mask = random.randint(0, secp256r1_r - 1) # commit-scalar = (rand + mask) mod r self.scalar = (self.rand + mask) % secp256r1_r assert self.scalar > 1 # COMMIT-ELEMENT = inverse(mask * PWE) temp = self.pwe * mask self.element = ECC.EccPoint(temp.x, Integer(secp256r1_p) - temp.y) auth = build_sae_commit(self.srcaddr, self.dstaddr, self.scalar, self.element) sendp(RadioTap() / auth)
def get_contract_Info(self): # La clé publique de l'utilisateur doit etre dans la base de donnée # le group doit avoir ete cree self.group_size = self.contract.caller().N() self.threshold = self.contract.caller().t() self.public_account = self.contract.caller().public_account() self.encrypted_public_account = [] for i in range(self.group_size): self.encrypted_public_account.append( EncryptedAccount( self.contract.caller().get_encrypted_public_account(i))) db = get_db() pk_sql = db.execute( 'SELECT * from eth_public_key WHERE account_address=?', (self.public_account, )).fetchone() pk_x = int(pk_sql['pk_x'], 0) pk_y = int(pk_sql['pk_y'], 0) self.key_point = ECC.EccPoint(pk_x, pk_y) * int(self.private_key, 0) db.close()
def process_commit(self, p): payload = str(p[Dot11Auth].payload) group_id = struct.unpack("<H", payload[:2])[0] pos = 2 self.peer_scalar = int(payload[pos:pos + 32].encode("hex"), 16) pos += 32 peer_element_x = int(payload[pos:pos + 32].encode("hex"), 16) peer_element_y = int(payload[pos + 32:pos + 64].encode("hex"), 16) self.peer_element = ECC.EccPoint(peer_element_x, peer_element_y) pos += 64 k = ((self.pwe * self.peer_scalar + self.peer_element) * self.rand).x keyseed = HMAC256("\x00" * 32, int_to_data(k)) kck_and_pmk = KDF_Length( keyseed, "SAE KCK and PMK", int_to_data((self.scalar + self.peer_scalar) % secp256r1_r), 512) self.kck = kck_and_pmk[0:32] self.pmk = kck_and_pmk[32:] self.send_confirm()
# 预备 生成两对椭圆曲线密钥,一对AES密钥 ''' NIST P-256: y^2 = x^3-3x+41058363725152142129326129780047268409114441015993725554835256314039467401291 modulo p = FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 G x = 48439561293906451759052585252797914202762949526041747995844080717082404635286 G y = 36134250956749795798585127919587881956611106672985015071877198253568414405109 ''' key1 = ECC.generate(curve='P-256') key1_pub = key1.public_key() key2 = ECC.generate(curve='P-256') key2_pub = key2.public_key() collect_d = key1.d point_G = ECC.EccPoint(x=48439561293906451759052585252797914202762949526041747995844080717082404635286, y=36134250956749795798585127919587881956611106672985015071877198253568414405109, curve='P-256') # 这里很奇怪,所有的地方都对ECC的实际应用语焉不详,都说“有办法把明文编码到椭圆曲线上”,但却从来不说怎么编码。 # 这里我们就用一个比较naive的方法,就是把它反过来,把点本身当成明文,而要做的AES_key就是把点hash一下,取前面的32位。 AES_key_point = ECC.generate(curve='p256').pointQ AES_key = SHA256.new(str(AES_key_point.xy).encode()).hexdigest()[:32].encode() print(key1_pub) print(key1) # 第一步 hash一下文件,并签名 filename_origin = 'SPN.pyx' h = SHA256.new()
def main(): global inst_cnt global cycle_cnt global ctx """main""" init_dmem() load_program() # curve point test (deterministic) inst_cnt = 0 cycle_cnt = 0 res = run_isoncurve(xexp, yexp) if not res: raise Exception('Test point (deterministic) should be on curve') ins_point_test = inst_cnt cyc_point_test = cycle_cnt # curve point test (random) #rand = Integer.random_range(min_inclusive=1, max_exclusive=P256_CURVE_ORDER) randkey = ECC.generate(curve='P-256') randx = int(randkey.public_key().pointQ.x.to_bytes(32).hex(), 16) randy = int(randkey.public_key().pointQ.y.to_bytes(32).hex(), 16) inst_cnt = 0 cycle_cnt = 0 res = run_isoncurve(randx, randy) if not res: raise Exception('Test point (deterministic) should be on curve') ins_point_test_rnd = inst_cnt cyc_point_test_rnd = cycle_cnt # scalar multiplication (deterministic) inst_cnt = 0 cycle_cnt = 0 pointexp = ECC.EccPoint(xexp, yexp, curve='p256') resref = pointexp*kexp init_dmem() xres, yres = run_scalarmult(xexp, yexp, kexp) resbn = ECC.EccPoint(xres, yres, curve='p256') if not resref == resbn: raise Exception('Wrong result for scalar point multiplication (deterministic)') ins_scalar_mult = inst_cnt cyc_scalar_mult = cycle_cnt # scalar multiplication (random) inst_cnt = 0 cycle_cnt = 0 randkey = ECC.generate(curve='P-256') randx = int(randkey.public_key().pointQ.x.to_bytes(32).hex(), 16) randy = int(randkey.public_key().pointQ.y.to_bytes(32).hex(), 16) randk = int(Integer.random_range(min_inclusive=1, max_exclusive=P256_CURVE_ORDER).to_bytes(32).hex(), 16) randp = ECC.EccPoint(randx, randy, curve='p256') resref = randp*randk init_dmem() xres, yres = run_scalarmult(randx,randy, randk) resbn = ECC.EccPoint(xres, yres, curve='p256') if not resref == resbn: raise Exception('Wrong result for scalar point multiplication (deterministic)') ins_scalar_mult_rand = inst_cnt cyc_scalar_mult_rand = cycle_cnt # ECDSA sign (deterministic) inst_cnt = 0 cycle_cnt = 0 init_dmem() rres, sres = run_sign(d, kexp, msg_digest_int) rresb = rres.to_bytes(32, byteorder='big', signed=False) sresb = sres.to_bytes(32, byteorder='big', signed=False) rsresb = b''.join([rresb, sresb]) verkey =ECC.construct(curve='p256', point_x=x, point_y=y, d=d) verifier = DSS.new(verkey, 'fips-186-3') try: verifier.verify(msg_digest, rsresb) except ValueError: raise Exception('ECDSA sign (deterministic) failed') ins_sign = inst_cnt cyc_sign = cycle_cnt # ECDSA sign (random (random key, random k, deterministic message digest)) inst_cnt = 0 cycle_cnt = 0 init_dmem() randkey = ECC.generate(curve='P-256') randd = int(randkey.d.to_bytes(32).hex(), 16) randk = int(Integer.random_range(min_inclusive=1, max_exclusive=P256_CURVE_ORDER).to_bytes(32).hex(), 16) rres, sres = run_sign(randd, randk, msg_digest_int) rresb = rres.to_bytes(32, byteorder='big', signed=False) sresb = sres.to_bytes(32, byteorder='big', signed=False) rsresb = b''.join([rresb, sresb]) verifier = DSS.new(randkey, 'fips-186-3') try: verifier.verify(msg_digest, rsresb) except ValueError: raise Exception('ECDSA sign (random) failed') ins_sign_rand = inst_cnt cyc_sign_rand = cycle_cnt # ECDSA verify (deterministic) inst_cnt = 0 cycle_cnt = 0 init_dmem() res = run_verify(xexp, yexp, rexp, sexp, msg_digest_int) if not res: raise Exception('ECDSA verifiy (deterministic) failed') ins_verify = inst_cnt cyc_verify = cycle_cnt # ECDSA verify (random) inst_cnt = 0 cycle_cnt = 0 init_dmem() randkey = ECC.generate(curve='P-256') randx = int(randkey.public_key().pointQ.x.to_bytes(32).hex(), 16) randy = int(randkey.public_key().pointQ.y.to_bytes(32).hex(), 16) signer = DSS.new(randkey, 'fips-186-3') signature = signer.sign(msg_digest) r = int.from_bytes(signature[0:32], byteorder='big', signed=False) s = int.from_bytes(signature[32:64], byteorder='big', signed=False) res = run_verify(randx, randy, r, s, msg_digest_int) if not res: raise Exception('ECDSA verifiy (rand) failed') ins_verify_rand = inst_cnt cyc_verify_rand = cycle_cnt print('=== Instructions ===') print('point test (deterministic): ' + str(ins_point_test)) print('point test (random): ' + str(ins_point_test_rnd)) print('scalar multiplication (deterministic): ' + str(ins_scalar_mult)) print('scalar multiplication (random): ' + str(ins_scalar_mult_rand)) print('ECDSA sign(deterministic): ' + str(ins_sign)) print('ECDSA sign(random): ' + str(ins_sign_rand)) print('ECDSA verify(deterministic): ' + str(ins_verify)) print('ECDSA verify(random): ' + str(ins_verify_rand)) print('\n=== Cycles ===') print('point test (deterministic): ' + str(cyc_point_test)) print('point test (random): ' + str(cyc_point_test_rnd)) print('scalar multiplication (deterministic): ' + str(cyc_scalar_mult)) print('scalar multiplication (random): ' + str(cyc_scalar_mult_rand)) print('ECDSA sign(deterministic): ' + str(cyc_sign)) print('ECDSA sign(random): ' + str(cyc_sign_rand)) print('ECDSA verify(deterministic): ' + str(cyc_verify)) print('ECDSA verify(random): ' + str(cyc_verify_rand))
print(C) np.savetxt("C.txt",C) ##################################################################################### #########################DECRYPTION################################################## ##################################################################################### ###################Loading encrypted picture######################################## f = open('Encrypted.txt','r') R_x=f.readline() R_y=f.readline() S_x=f.readline() S_y=f.readline() f.close() C= np.loadtxt("C.txt") R=ECC.EccPoint(x=R_x,y=R_y) S=ECC.EccPoint(x=S_x,y=S_y) plt.imshow(C,cmap='gray') plt.show() D=Decryption(R,S,C) print("Picture decrypted") plt.imshow(D,cmap='gray') plt.show() #######################TEST FOR MERGING IMAGES############ # img=cv2.imread("Test.png",cv2.IMREAD_GRAYSCALE) # # img=cv2.imread("test_image.jpg",cv2.IMREAD_GRAYSCALE) # plt.imshow(img,cmap='gray') # plt.show() # (array_of_images,m,n)=preprocessing(img)
pk_x = ECC_key.pointQ.x pk_y = ECC_key.pointQ.y db.execute( "INSERT INTO eth_public_key (account_address, pk_x, pk_y) VALUES (?,?,?)", [account_address, hex(pk_x), hex(pk_y)]) # retrieving of a list of public keys address = [ account_address, ] placeholders = ', '.join('?' for account in address) public_keys = db.execute( "SELECT * from eth_public_key WHERE account_address IN (%s)" % placeholders, address).fetchall() # ciphering of public account public_account_private_key = '0x0d1f7c294e32490c48eaf6e9bbcc24380227334624bfad2f79736116a5408103' cipher_account_list = [] for row in public_keys: pk_x = int(row['pk_x'], 0) pk_y = int(row['pk_y'], 0) key_point = ECC.EccPoint(pk_x, pk_y) * int(public_account_private_key, 0) sym_key = HKDF((str(key_point.x) + str(key_point.y)).encode(), 32, b'', SHA256) aes = AES.new(sym_key, AES.MODE_CCM) nonce = aes.nonce enc_private_key = aes.encrypt(public_account_private_key.encode()) tag = aes.digest() encryption = {'private_key': enc_private_key, 'tag': tag, 'nonce': nonce} cipher_account_list.append(encryption)
public_key = eval(key.get_public_key()) # print(public_key) # 为每个问题的选项生成对应的点 """ 问题1:我好看么 好看/不好看 问题2:你心中的主席是 张三/李四 """ order = key.order G = key.G selections = [{'好看': string_to_point('好看', get_point_dic('好看')), '不好看': string_to_point('不好看', get_point_dic('不好看'))}, { '张三': string_to_point('张三', get_point_dic('张三')), '李四': string_to_point('李四', get_point_dic('李四'))}] K = ECC.EccPoint(Integer(int(public_key['x'])), Integer(int(public_key['y']))) def random_result(votes, num, G, K, order): vote_c1 = [] vote_c2 = [] hash_c1 = [] hash_c2 = [] for i in range(num): vote_c1_i = [] vote_c2_i = [] hash_c1_i = [] hash_c2_i = [] for j in range(len(votes)): len_j = len(votes[j]) ran = random_int.randint(0, len_j-1)
def public_key_bytes_to_point(key_bytes, curve='P-256'): return ECC.EccPoint(bytes_to_long(key_bytes[1:33]), bytes_to_long(key_bytes[33:]), curve)
def point_on_curve(x, y, curve="p256"): try: point = ECC.EccPoint(x, y) except ValueError: return False return True
def pad_b64(b): missing_padding = len(b) % 4 if missing_padding: b += '='* (4 - missing_padding) return b def b64_to_bytes(b): b = pad_b64(b) return b64decode(b, "-_") def b64_to_num(b): b = pad_b64(b) return int.from_bytes(b64decode(b, "-_"), "big") alice_public = ECC.EccPoint(b64_to_num(alice["x"]), b64_to_num(alice["y"]), "P-256") alice_private = b64_to_num(alice["d"]) bob_public = ECC.EccPoint(b64_to_num(bob["x"]), b64_to_num(bob["y"]), "P-256") bob_private = b64_to_num(bob["d"]) shared_secret_bob = bob_private*alice_public shared_secret_alice = alice_private*bob_public assert shared_secret_alice == shared_secret_bob key = shared_secret_alice.x.to_bytes() cts = [ "L09uZOOqgcCBo9Fa50ABqJmmmnSL9wRO-M-LjGuhGSM",