def test_crypto_generichash(self): pysodium.crypto_generichash(b'howdy') pysodium.crypto_generichash(b'howdy', outlen=4) pysodium.crypto_generichash(b'howdy', outlen=6) pysodium.crypto_generichash(b'howdy', outlen=8) state = pysodium.crypto_generichash_init() pysodium.crypto_generichash_update(state, b'howdy') pysodium.crypto_generichash_final(state) state = pysodium.crypto_generichash_init(outlen=6) pysodium.crypto_generichash_update(state, b'howdy') pysodium.crypto_generichash_final(state, outlen=6)
def on_message(client, userdata, msg): # neu Ib goi if (msg.topic == url_client2_publicKey): global n_a global n_b global IC_b global ID_b global C_ca_b global Pk global Lk global massage_authen global n_b_templ global n_a_templ ms = (msg.payload).decode("utf-8") ms = (ms.split(',')) n_b_templ = n_b = ms[1] ID_b = ms[2] IC_b = ms[3] C_ca_b = ms[4] # tinh khoa cong khai P b,A = C + P A · H(P A , I A ). P_client = ECC.create_key_to_third_party(int(C_ca_b), ID_b, int(IC_b)) # P = s v,B · P b,A . P = ECC.scalar_mult(private_key, ECC.x_to_Point(P_client)) if (P[0]): state = pysodium.crypto_generichash_init(32) pysodium.crypto_generichash_update(state, str(P[0]).encode()) # Pre Link Key, P K Pk = pysodium.crypto_generichash_final(state, 32).hex() # α A = Auth(P K , (P A , P B , ρ A , ρ B )). massage_authen = str(IC_a) + str(IC_b) + n_a + n_b massage2 = aead_chacha20poly1305_encrypt(Pk, massage_authen, n_a) # gui cho B client.publish(url_client1_publicKey_massage2, massage2, qos=1) # lang nghe α B = Auth(P K , (P B , P A , ρ B , ρ A )). elif (msg.topic == url_client2_publicKey_massage2): ms = (msg.payload).decode("utf-8") try: verify = aead_chacha20poly1305_decrypt(Pk, ms, n_b) if (verify == massage_authen): Lk = str(Pk + n_a + n_b).encode() state2 = pysodium.crypto_generichash_init(32) pysodium.crypto_generichash_update(state2, Lk) Lk = pysodium.crypto_generichash_final(state2, 32).hex() except (ValueError): print(b'ValueError') # massage nhan dc else: ms = (msg.payload).decode("utf-8") ms = aead_chacha20poly1305_decrypt(Lk, (ms), n_b) print('Message nhận: ' + ms)
def test_crypto_generichash(self): r=pysodium.crypto_generichash(b'howdy') pysodium.crypto_generichash(b'howdy', outlen=4) r6=pysodium.crypto_generichash(b'howdy', outlen=6) pysodium.crypto_generichash(b'howdy', outlen=8) state = pysodium.crypto_generichash_init() pysodium.crypto_generichash_update(state, b'howdy') r1=pysodium.crypto_generichash_final(state) state = pysodium.crypto_generichash_init(outlen=6) pysodium.crypto_generichash_update(state, b'howdy') r61=pysodium.crypto_generichash_final(state, outlen=6) self.assertEqual(r, r1) self.assertEqual(r6, r61)
def blake2b(self, data, addr, server=False): # ECDH_AED_accept = None addrStr = sts_utility.addrToString(addr) proposeResp = sts_utility.deconstructPropose(data) # print(STS.STSConnectionStates) # if addrStr in STS.STSConnectionStates.keys(): myECDHPK, myECDHSK = STS.STSConnectionStates[addrStr]['keys'] # TODO verification scalarmult_q = pysodium.crypto_scalarmult_curve25519( myECDHSK, proposeResp['K']) genericHash = pysodium.crypto_generichash_init(outlen=64) genericHash = pysodium.crypto_generichash_update( genericHash, scalarmult_q) if not server: genericHash = pysodium.crypto_generichash_update( genericHash, myECDHPK) genericHash = pysodium.crypto_generichash_update( genericHash, proposeResp['K']) else: genericHash = pysodium.crypto_generichash_update( genericHash, proposeResp['K']) genericHash = pysodium.crypto_generichash_update( genericHash, myECDHPK) genericHash = pysodium.crypto_generichash_final(genericHash, outlen=64) STS.STSConnectionStates[addrStr]['session_key'] = genericHash # STS.STSConnectionStates[addrStr]['phase'] = 1 STS.STSConnectionStates[addrStr]['time'] = int(time.time())
def hash_handler(infile=None, k='', outlen=16): fd = inputfd(infile) # calculate hash sum of data state = nacl.crypto_generichash_init(outlen=outlen, k=k or '') while True: block = fd.read(BLOCK_SIZE) if not block.strip(): break state = nacl.crypto_generichash_update(state, block) if fd != sys.stdin: fd.close() return nacl.crypto_generichash_final(state, outlen=outlen)
def hash_handler(infile=None, k='', outlen=16): fd = inputfd(infile) # calculate hash sum of data state = nacl.crypto_generichash_init() while True: block = fd.read(BLOCK_SIZE) if not block.strip(): break state = nacl.crypto_generichash_update(state, block) if fd != sys.stdin: fd.close() return nacl.crypto_generichash_final(state)
def verify_challenge(conn): # read challenge challenge = conn.read(1 + 1 + 8 + 32) # n,k,ts,sig if (len(challenge) != 42): fail(conn) n, tmp = pop(challenge, 1) n = n[0] k, tmp = pop(tmp, 1) k = k[0] ts, tmp = pop(tmp, 8) ts = struct.unpack("Q", ts)[0] sig, tmp = pop(tmp, 32) # read request req_type = conn.read(1) if req_type[0] == READ: payload = conn.read(32) if len(payload) != 32: fail(conn) else: payload = conn.read(64) if len(payload) != 64: fail(conn) req = req_type + payload # read mac key key = load_blob('', "key", 32) if not key: fail(conn) tosign = challenge[:10] state = pysodium.crypto_generichash_init(32, key) pysodium.crypto_generichash_update(state, req) pysodium.crypto_generichash_update(state, tosign) mac = pysodium.crypto_generichash_final(state, 32) # poor mans const time comparison if (sum(m ^ i for (m, i) in zip(mac, sig))): fail(conn) now = datetime.datetime.now().timestamp() if now - (RL_Timeouts[(n, k)] + rl_gracetime) > ts: # solution is too old fail(conn) solsize = equihash.solsize(n, k) solution = conn.read(solsize) if len(solution) != solsize: fail(conn) seed = b''.join([challenge, req]) if not equihash.verify(n, k, seed, solution): fail(conn) handler(conn, req)
def verify_handler(infile=None, outfile=None, basedir=None): if not infile or infile == '-': fd = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin else: fd = open(infile, 'rb') if not outfile or outfile == '-': outfd = sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout else: outfd = open(outfile, 'wb') # calculate hash sum of data state = nacl.crypto_generichash_init() block = fd.read(int(BLOCK_SIZE / 2)) while block: # use two half blocks, to overcome # sigs spanning block boundaries if len(block) == (BLOCK_SIZE / 2): next = fd.read(int(BLOCK_SIZE / 2)) else: next = b'' fullblock = block + next sigoffset = fullblock.rfind(SIGPREFIX) if 0 <= sigoffset <= (BLOCK_SIZE / 2): sig = b85decode(fullblock[sigoffset + len(SIGPREFIX):]) block = block[:sigoffset] next = b'' elif len(fullblock) < (BLOCK_SIZE / 2) + nacl.crypto_sign_BYTES: sig = fullblock[-nacl.crypto_sign_BYTES:] block = fullblock[:-nacl.crypto_sign_BYTES] next = b'' state = nacl.crypto_generichash_update(state, block) if outfd: outfd.write(block) block = next hashsum = nacl.crypto_generichash_final(state) sender, hashsum1 = publickey.verify(sig + hashsum, basedir=basedir) or ([], '') if sender and hashsum == hashsum1: sys.stderr.write("good message from %s\n" % sender) else: sys.stderr.write('verification failed\n') if fd != sys.stdin: fd.close() if outfd != sys.stdout: outfd.close()
def buffered_sign(self,infd,outfd, armor=None): # calculate hash sum of data state = nacl.crypto_generichash_init() while True: block = infd.read(BLOCK_SIZE) if not block.strip(): break state = nacl.crypto_generichash_update(state, block) outfd.write(block) hashsum = nacl.crypto_generichash_final(state) # sign hashsum sig = self.sign(hashsum)[:nacl.crypto_sign_BYTES] #print 'clearing' #self.clear() if armor: sig = b"".join((SIGPREFIX, b85encode(sig))) outfd.write(sig)
def buffered_sign(self, infd, outfd, armor=None): # calculate hash sum of data state = nacl.crypto_generichash_init() while True: block = infd.read(BLOCK_SIZE) if not block.strip(): break state = nacl.crypto_generichash_update(state, block) outfd.write(block) hashsum = nacl.crypto_generichash_final(state) # sign hashsum sig = self.sign(hashsum)[:nacl.crypto_sign_BYTES] #print 'clearing' #self.clear() if armor: sig = b"".join((SIGPREFIX, b85encode(sig))) outfd.write(sig)
def verify_handler(infile=None, outfile=None, basedir=None): # provides a high level function to verify signed files # infile specifies the filename of the input file, # if '-' or not specified it uses stdin # outfile specifies the filename of the output file, # basedir provides a root for the keystores # this function also handles buffering. fd = inputfd(infile) outfd = outputfd(outfile) # calculate hash sum of data state = nacl.crypto_generichash_init() block = fd.read(int(BLOCK_SIZE/2)) while block: # use two half blocks, to overcome # sigs spanning block boundaries if len(block)==(BLOCK_SIZE/2): next=fd.read(int(BLOCK_SIZE/2)) else: next='' fullblock = "%s%s" % (block, next) sigoffset = fullblock.rfind(SIGPREFIX) if 0 <= sigoffset <= (BLOCK_SIZE/2): sig = b85decode(fullblock[sigoffset+len(SIGPREFIX):]) block = block[:sigoffset] next = '' elif len(fullblock)<(BLOCK_SIZE/2)+nacl.crypto_sign_BYTES: sig = fullblock[-nacl.crypto_sign_BYTES:] block = fullblock[:-nacl.crypto_sign_BYTES] next = '' state = nacl.crypto_generichash_update(state, block) if outfd: outfd.write(block) block = next if fd != sys.stdin: fd.close() if outfd != sys.stdout: outfd.close() hashsum = nacl.crypto_generichash_final(state) sender, hashsum1 = publickey.verify(sig+hashsum, basedir=basedir) or ([], '') if sender and hashsum == hashsum1: return sender
def sign_handler(infile=None, outfile=None, self=None, basedir=None, armor=False): # provides a high level function to sign files # infile specifies the filename of the input file, # if '-' or not specified it uses stdin # outfile specifies the filename of the output file, # if unspecified but armor is, or if '-' or # infile is unspecified, then it uses stdout # otherwise it appends '.sig' to infile # armor instructs the function to output ascii # self specifies the sender for signing the message # basedir provides a root for the keystores # this function also handles buffering. fd = inputfd(infile) if (not outfile and armor) or outfile == '-' or (not infile or infile == '-'): outfd = sys.stdout else: outfd = open(outfile or infile+'.sig','w') # calculate hash sum of data state = nacl.crypto_generichash_init() while True: block = fd.read(BLOCK_SIZE) if not block.strip(): break state = nacl.crypto_generichash_update(state, block) outfd.write(block) hashsum = nacl.crypto_generichash_final(state) me = publickey.Identity(self, basedir=basedir) # sign hashsum sig = me.sign(hashsum)[:nacl.crypto_sign_BYTES] me.clear() if armor: sig = "%s%s" % (SIGPREFIX, b85encode(sig)) outfd.write(sig) if fd != sys.stdin: fd.close() if outfd != sys.stdout: outfd.close()
def buffered_verify(infd, outfd, basedir, self=None): # calculate hash sum of data state = nacl.crypto_generichash_init() block = infd.read(int(BLOCK_SIZE / 2)) while block: # use two half blocks, to overcome # sigs spanning block boundaries if len(block) == (BLOCK_SIZE / 2): next = infd.read(int(BLOCK_SIZE / 2)) else: next = "" fullblock = "%s%s" % (block, next) sigoffset = fullblock.rfind(SIGPREFIX) if 0 <= sigoffset <= (BLOCK_SIZE / 2): sig = b85decode(fullblock[sigoffset + len(SIGPREFIX) : sigoffset + len(SIGPREFIX) + 80]) block = block[:sigoffset] next = "" elif len(fullblock) < (BLOCK_SIZE / 2) + nacl.crypto_sign_BYTES: sig = fullblock[-nacl.crypto_sign_BYTES :] block = fullblock[: -nacl.crypto_sign_BYTES] next = "" state = nacl.crypto_generichash_update(state, block) if outfd: outfd.write(block) block = next hashsum = nacl.crypto_generichash_final(state) if self: # verify specific key sender, hashsum1 = self.verify(sig + hashsum) or ([], "") else: # find corresponding key sender, hashsum1 = publickey.verify(sig + hashsum, basedir=basedir) or ([], "") if sender and hashsum == hashsum1: return sender
def buffered_verify(infd, outfd, basedir, self=None): # calculate hash sum of data state = nacl.crypto_generichash_init() block = infd.read(int(BLOCK_SIZE / 2)) while block: # use two half blocks, to overcome # sigs spanning block boundaries if len(block) == (BLOCK_SIZE / 2): next = infd.read(int(BLOCK_SIZE / 2)) else: next = b'' fullblock = b"".join((block, next)) sigoffset = fullblock.rfind(SIGPREFIX) if 0 <= sigoffset <= (BLOCK_SIZE / 2): sig = b85decode(fullblock[sigoffset + len(SIGPREFIX):sigoffset + len(SIGPREFIX) + 80]) block = block[:sigoffset] next = b'' elif len(fullblock) < (BLOCK_SIZE / 2) + nacl.crypto_sign_BYTES: sig = fullblock[-nacl.crypto_sign_BYTES:] block = fullblock[:-nacl.crypto_sign_BYTES] next = b'' state = nacl.crypto_generichash_update(state, block) if outfd: outfd.write(block) block = next hashsum = nacl.crypto_generichash_final(state) if self: # verify specific key sender, hashsum1 = self.verify(sig + hashsum) or ([], '') else: # find corresponding key sender, hashsum1 = verify(sig + hashsum, basedir=basedir) or ([], '') if sender and hashsum == hashsum1: return sender
def sign_handler(infile=None, outfile=None, self=None, basedir=None, armor=False): if not infile or infile == '-': fd = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin else: fd = open(infile, 'rb') if (not outfile and armor) or outfile == '-': outfd = sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout else: outfd = open(outfile or infile + '.sig', 'wb') # calculate hash sum of data state = nacl.crypto_generichash_init() while True: block = fd.read(BLOCK_SIZE) if not block.strip(): break state = nacl.crypto_generichash_update(state, block) outfd.write(block) hashsum = nacl.crypto_generichash_final(state) me = publickey.Identity(self, basedir=basedir) # sign hashsum sig = me.sign(hashsum)[:nacl.crypto_sign_BYTES] me.clear() if armor: outfd.write(SIGPREFIX) outfd.write(b85encode(sig)) else: outfd.write(sig) if fd != sys.stdin: fd.close() if outfd != sys.stdout: outfd.close()
def create_challenge(conn): req = conn.read(65) if req[0] == READ: if len(req) != 33: fail(conn) elif len(req) != 65: fail(conn) now = datetime.datetime.now().timestamp() id = binascii.hexlify(req[1:33]).decode() diff = load_blob(id, 'difficulty', 9) # ts: u32, level: u8, count:u32 if not diff: # no diff yet, use easiest hardness n = Difficulties[0]['n'] k = Difficulties[0]['k'] level = 0 count = 0 else: level = struct.unpack("B", diff[0:1])[0] count = struct.unpack("I", diff[1:5])[0] ts = struct.unpack("I", diff[5:])[0] if level >= len(Difficulties): print("invalid level in rl_ctx:", level) level = len(Difficulties) - 1 count = 0 elif ((now - rl_decay) > ts and level > 0): # cooldown, decay difficulty periods = int((now - ts) // rl_decay) if level >= periods: level -= periods else: level = 0 count = 0 else: # increase hardness if count >= rl_threshold and (level < len(Difficulties) - 1): count = 0 level += 1 else: count += 1 n = Difficulties[level]['n'] k = Difficulties[level]['k'] if (level == len(Difficulties) - 1) and count > rl_threshold * 2: print( f"{normal}alert{normal}: someones trying (%d) really hard at: %s" % (196, 253, count, id)) rl_ctx = b''.join([ struct.pack("B", level), # level struct.pack("I", count), # count struct.pack('I', int(now)) # ts ]) if (verbose): print("rl difficulty", { "level": level, "count": count, "ts": int(now) }) try: save_blob(id, 'difficulty', rl_ctx) except FileNotFoundError: if diff: raise challenge = b''.join([bytes([n, k]), struct.pack('Q', int(now))]) key = load_blob('', "key", 32) if not key: key = pysodium.randombytes(32) save_blob('', 'key', key) state = pysodium.crypto_generichash_init(32, key) pysodium.crypto_generichash_update(state, req) pysodium.crypto_generichash_update(state, challenge) sig = pysodium.crypto_generichash_final(state, 32) resp = b''.join([challenge, sig]) conn.send(resp)