def test_protocol(): start_time = time.time() Alice = DiffieHellman() q = Alice.get_generator() p = Alice.get_prime() Bob = DiffieHellman(generator=q, prime=p) # Compute respective public keys PU_A = Alice.get_public_key() PU_B = Bob.get_public_key() # Compute shared session key K_A = Alice.get_session_key(PU_B) K_B = Bob.get_session_key(PU_A) assert K_A == K_B #CSPRNG bbs = BlumBlumShub(q=383, p=503) Alice_secret_key = bbs.generate(seed=K_A, key_len=128) Bob_secret_key = bbs.generate(seed=K_B, key_len=128) assert Alice_secret_key == Bob_secret_key assert len(Alice_secret_key) == 128 # From Alice to Bob message = "Hi Bob, this is a message that should be encrypted properly" enc_message = encrypt(message, Alice_secret_key) dec_message = decrypt(enc_message, Bob_secret_key) assert message in dec_message # From Bob to Alice message = "Hi Alice, this is also a message that should be encrypted properly" enc_message = encrypt(message, Bob_secret_key) dec_message = decrypt(enc_message, Alice_secret_key) assert message in dec_message total_time = (time.time() - start_time) print(f'##########\nPassed protocol test in {total_time}s\n##########')
def encrypt_and_tag(key, nonce, data, adata): tag_key = encrypt(key, nonce, chr(0x00) * 64) tag_key = tag_key[:32] ciphertext = encrypt(key, nonce, data, counter=1) tag_input = len_bytes(len(adata)) + adata + len_bytes( len(ciphertext)) + ciphertext ciphertext_tag = tag(tag_key, tag_input) return ciphertext + ciphertext_tag
def verify_and_decrypt(key, nonce, data, adata): ciphertext, ciphertext_tag = data[:-16], data[-16:] tag_key = encrypt(key, nonce, chr(0x00) * 64) tag_key = tag_key[:32] tag_input = len_bytes(len(adata)) + adata + len_bytes( len(ciphertext)) + ciphertext if not compare_digest(tag(tag_key, tag_input), ciphertext_tag): print 'Got a bad tag, aborting decryption process' return None return encrypt(key, nonce, ciphertext, counter=1)
def test_header(self): from cipher import cipher HEADER = cipher.HEADER cipher.HEADER = b"foo" secret = encrypt(self.passwd, self.txt) with self.assertRaises(Exception) as ctx: decrypt(self.passwd, secret) self.assertEqual(type(ctx.exception), RuntimeError) self.assertEqual(str(ctx.exception), "Missing header, cannot decrypt") cipher.HEADER = HEADER secret = encrypt(self.passwd, self.txt) self.assertEqual(decrypt(self.passwd, secret), self.txt)
def register(self): if (self.address == None) or (self.abi == None): contract_source_code = None try: contract_source_code = self.__readContract() except IOError: return -1 compiled = compile_source(contract_source_code,import_remappings=["-"]) # Compiled source code contract_interface = compiled['<stdin>:Log'] #Instantiate and deploy contract Log = self.w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) salt = self.__generateSalt() pk = None while pk == None: try: pk = self.__getPrivateKey() except ValueError: pass ivs = self.__generateIvs() salt = cipher.encrypt(salt,pk,ivs) # Submit the transaction that deploys the contract tx_hash = Log.constructor(salt).transact() # Wait for the transaction to be mined, and get the transaction receipt tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash) # Create the contract instance with the newly-deployed address self.contract = self.w3.eth.contract( address=tx_receipt.contractAddress, abi=contract_interface['abi'], ) if self.contract.functions.getElem().call() == 0: self.address = tx_receipt.contractAddress self.abi = contract_interface['abi'] my_file = Path(self.pathInfo) with open(my_file,'w') as f: f.write(tx_receipt.contractAddress + '\n') f.write(str(contract_interface['abi']) + '\n') my_file = Path(self.pathIvs) with open(my_file,'wb') as f: for i in range(len(ivs)): f.write(ivs[i]) return 0 else: return -1 else: return 1
def send(): # event is passed by binders. msg = my_msg.get() my_msg.set("") # Clears input field. r = post('http://127.0.0.1:5000/qkuser/A', json={"receiver": "B"}) print(r.json()) data = r.json() print("Symmetric key retrieved for B: " + data['status']) qkey = data['status'] nonce = utils.random(secret.SecretBox.NONCE_SIZE) print("Nonce") print(nonce) print("Message") print(msg) ctext = cipher.encrypt(msg, qkey, nonce) print("Ciphertext") print(ctext) print("Qkey") print(qkey) texttosend = str(ctext) + "###" + base64.encodebytes(nonce).decode("utf-8") client_socket.send(bytes(texttosend, "utf8")) if msg == "{quit}": client_socket.close() top.quit()
def encryption_button(request): if request.method == "POST": data = json.loads(request.body) encryptedData = encrypt(data['text'], int(data['key1']), int(data['key2'])) responseJson = json.dumps({'text': encryptedData}, ensure_ascii=False) return HttpResponse(responseJson, content_type='application/json')
def userLogin(): print('Enter your username: '******'') username = input() if not isNonZeroFile('config.json'): with open('config.json', 'w') as f: json.dump({username: ''}, f) with open('config.json', 'r') as f: data = json.load(f) if username not in data: userRegistration(username) # register user else: while True: password = winGetPass() encryptedPass = cipher.encrypt(password, cipherKey[username]) if isEqualPassword(encryptedPass, data[username].encode('UTF-8')): break print('Password incorrect!')
def userRegistration(username): print('First time using this program? Need your login credentials') while True: pw1 = winGetPass() pw2 = winGetPass('Enter password again: ') if isEqualPassword(pw1, pw2): cipherSuite = cipher.generateCipherSuite( ) # generate a cipher suite cipherKey[username] = cipherSuite encryptedPass = cipher.encrypt(pw1, cipherSuite) configData[username] = encryptedPass.decode( 'UTF-8') # string for JSON with open('config.json', 'w') as f: data = json.load(f) # get dictionary in json updatedData = dict( data.items() + configData.items() ) # make new dict with json values + new user json.dump(updatedData, f) # write to json break print('Passwords did not match!')
def handle_tcp(self, remote): sock = self.request sock_list = [sock, remote] while 1: read_list, _, _ = select(sock_list, [], []) if remote in read_list: data = remote.recv(8192) if not data: break enc = cipher.encrypt(data) length = len(enc) logging.debug('send data to client: {}'.format(length)) sock.send(u16_to_bytes(length)) if (sock.send(enc) <= 0): break if sock in read_list: data = safe_recv(sock, 2) if data is None: break length = bytes_to_int(data) logging.debug('fetching data from client: {}'.format(length)) data = safe_recv(sock, length) if data is None: break dec = cipher.decrypt(data) logging.debug('send data to server: {}'.format(len(dec))) if (remote.send(dec) <= 0): logging.debug('send to server error') break
def handle_tcp(self, remote): sock = self.request sock_list = [sock, remote] while True: read_list, _, _ = select(sock_list, [], []) if remote in read_list: data = safe_recv(remote, 2) if data is None: break length = bytes_to_int(data) logging.debug('receiving data from remote: {}'.format(length)) data = safe_recv(remote, length) if not data: break dec = cipher.decrypt(data) if (sock.send(dec) <= 0): break if sock in read_list: data = sock.recv(8192) if not data: break enc = cipher.encrypt(data) length = len(enc) remote.send(u16_to_bytes(length)) logging.debug('send data to server: {}'.format(length)) if (remote.send(enc) <= 0): break
def test_AES(): start_time = time.time() key = '11100101010001100001110100011111100101000010010011000010011111101101001110010110101101010101011101101101110010000111101001000111' enc = encrypt('Hello World!', key) dec = decrypt(enc, key) assert 'Hello World!' in dec total_time = (time.time() - start_time) print(f'##########\nPassed AES test in {total_time}s\n##########')
def encrypt(to_proc, key, is_file, out=None): if is_file: to_proc = read_path(to_proc) if out: cipher.write(out, key, to_proc) else: sys.stdout.write(cipher.encrypt(key, to_proc))
def test_encrypt(self): total = 100 for i in range(total): self.secrets.append(encrypt(self.passwd, self.txt)) for i in range(total): for j in range(i + 1, total): self.assertNotEqual(self.secrets[i], self.secrets[j])
def sendmsg(): """Encrypts plaintext into ciphertext and sends it to the other part""" if session['secret_key'] is not None: msg = request.form['msg'] msg = encrypt(plaintext=msg, key=session['secret_key']) #Cannot serialize bytes in JSON, so convert it to string over the network msg = str(base64.encodebytes(msg), 'utf-8') url = session['endpoint'] + '/getmsg' res = requests.post(url, json={'msg': msg}) return redirect(url_for('index'))
def _send_frame(self, data, ostream, frame_type=None, conn_id=None): if frame_type is not None: self._record("send", conn_id, data) plaintext = struct.pack("!BI", frame_type, conn_id) + data # self._log.debug("send frame, type=%d, id=%d" % (frame_type, conn_id)) else: plaintext = data ciphertext = cipher.encrypt(self._config["key"], plaintext) ostream.write(len(ciphertext)) ostream.write(ciphertext)
def saveEntry(entry, activeUser): connection = connectDatabase() cursor = connection.cursor() insert_entry = ('INSERT INTO entry (title, text, user) VALUES (%s, %s, %s)') entry_data = (entry.title, cipher.encrypt(activeUser,entry.text), activeUser) cursor.execute(insert_entry, entry_data) connection.commit() cursor.close() connection.close()
def pack_pb(self, pb, key = None): """Given a protocol buffer pb, serialize and encrypt any private field, then serialize and encrypt the whole buffer, and return a blob. If key is set, use it as the tableKey, otherwise use .table_key.""" # Separately encrypt a .private field. Replace it with .private_bytes. # If .user_key isn't set, it's not an error, but it won't encrypt. if pb.HasField("private") and self.user_key is not None: s = pb.private.SerializeToString() b = encrypt(self.user_key, s) pb.private_bytes = b pb.ClearField("private") s = pb.SerializeToString() # Encrypt the string s, using the provided key, or .table_key, or None. if key is None: key = self.table_key if key is None: return s return encrypt(key, s)
def main(): loop = True while loop == True: inputtext = input("Please enter a string: (q to Quit) ") if inputtext == "q": print("Goodbye!") loop = False break encrypted = cipher.encrypt(inputtext) decryptinput = input("Would you like to decrypt your message?: (y/n)") if decryptinput == "y": decrypted = cipher.decrypt(encrypted[0], encrypted[1]) decryptloop = False elif decryptinput == "n": decryptloop = False
def main(): print("***Everything is case sensitive***") message = '' while message != 'q': message = input("What is your message? To quit enter 'q': ") if message == 'q': # solely used for the first iteration, if input is q then end loop break encryption = cipher.encrypt(message) print('Encrypted message:\n', encryption[0], "\nCipher Dictionary:\n", encryption[1]) response = input("Would you like to decrypt? y/n: ") if response == 'y': # Asks if user wants to decrypt decryption = cipher.decrypt(encryption[0], encryption[1]) print("Decrypted message:", decryption) print("'q' detected! Terminating sequence.")
def Main(): keycheck = "password" menuOption = "0" print ("Welcome to the TauNet client program!\n" "Please note: Any input to the system must be surrounded by quotes\n") key = input("Please enter your TauNet key: ") while(keycheck != key): print "That is an incorrect key.\n" key = input("Please try again or enter Q to quit: ") if key == "Q": menuOption = "Q" print "Thanks for using TauNet!" break while(menuOption != "Q"): menuOption = input(("What would you like to do?\n" "1: Message a user\n" "Q: Quit\n")) if menuOption == "Q": print "Thanks for using TauNet!\n" break elif menuOption == "1": userList = displayUserList() msgOption = input(("Enter the number corresponding to the user you " "would like to message: ")) #this separates the user and domain from the entire row of the userlist.csv parser = userList[int(msgOption)] user = parser.split(',')[0] user = user[1:] domain = parser.split(',')[1] header = "version: " + version + "\r\nfrom: " + me + "\r\nto: " + user[1:-1] + "\r\n\r\n" msg = createMsg(header) msg = cipher.encrypt(msg, key) send(msg, domain) else: "Invalid choice. Please try again.\n"
def test_key_works(i): assert decrypt(encrypt('test', i), i) == 'test'
def handle(self): logging.info("got connection from {}".format(self.client_address[0])) data = safe_recv(self.request, 1) if data is None: return if data[0] != 5: logging.error("socks version not 5 but {}".format(data[0])) return data = safe_recv(self.request, 1) if data is None: return length = bytes_to_int(data) methods = safe_recv(self.request, length) if methods is None: return if b'\x00' not in methods: logging.error('client not support bare connect') return logging.debug('got client supported methods: {}'.format(methods)) # Send initial SOCKS5 response (VER, METHOD) self.request.sendall(b'\x05\x00') logging.debug('replied ver, method to client') data = safe_recv(self.request, 4) if data is None: logging.error('ver, cmd, rsv, atyp not received') return logging.debug('ver, cmd, rsv, atyp = {}'.format(data)) if len(data) != 4: logging.error("packet loss") return ver, cmd, rsv, atyp = data if ver != 5: logging.error('ver should be 05: {}'.format(ver)) return if cmd == 1: # CONNECT logging.info('client cmd type: connect') elif cmd == 2: # BIND logging.info('client cmd type: bind') else: logging.error('bad cmd from client: {}'.format(cmd)) return if atyp == ATYP_IPV6: logging.error('do not support IPV6 yet') return elif atyp == ATYP_DOMAIN: addr_len = ord(self.request.recv(1)) addr = self.request.recv(addr_len) elif atyp == ATYP_IPV4: addr = self.request.recv(4) addr = str(ipaddress.ip_address(addr)).encode() else: logging.error('bad atyp value: {}'.format(atyp)) return addr_port = self.request.recv(2) logging.info('want to access {}:{}'.format( addr.decode(), int.from_bytes(addr_port, 'big'))) remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: remote.connect((SERVER_IP, SERVER_PORT)) except: logging.error('cannot connect to lightsocks server.') return D['R'] += 1 logging.info('connected proxy server [{}]'.format(D['R'])) # Reply to client to estanblish the socks v5 connection reply = b"\x05\x00\x00\x01" reply += socket.inet_aton('0.0.0.0') reply += struct.pack("!H", 0) self.request.sendall(reply) # encrypt address before sending it addr = cipher.encrypt(addr) dest_address = bytearray() dest_address += len(addr).to_bytes(1, 'big') dest_address += addr dest_address += addr_port remote.sendall(dest_address) try: self.handle_tcp(remote) except Exception as e: logging.error('Got Exception: {}'.format(e)) finally: remote.close() D['R'] -= 1 logging.info('disconnected from proxy server [{}]'.format(D['R']))
bits = inp() p = generateLargePrime(int(bits/2)) q = generateLargePrime(int(bits/2)) n = int(p*q) #key length O = (p-1)*(q-1) #Euler's totient function e = 2**16 + 1 #Default value -- a well known prime that works well most of the time if gcd (e,O) != 1: #must be coprime e = generateLargePrime (17) raw_message = input("Please enter a message to be encrypted: ") m = convert_to_hex(raw_message) #encoded hex message to be used for RSA #d * e = 1 (mod O) => linear diophantine: e(d) + O(y) = 1 -- trying to find d #Implement Extended Euclidean Algorithm d = EEA (O , e, 1, 0, 0, 1) #prevent d with negative value if d < 0: d += (1 + abs(d)//O)*O c = cipher.encrypt (int(m, 16), e, n) write_to_file(raw_message, m, c, n, e, d) print("Message successfully encrypted and details stored in RSA.txt!") except: print("Something bad happened. This either means you did something naughty or Parsa's program has bug(s). This error message is useless for debugging, but at least it's not ugly. If you know what went wrong, please submit a pull request! Have a nice day!")
def test_encrypt_success(): assert cipher.encrypt("ABC", 1) == "BCD" assert cipher.encrypt("ABC", 0) == "ABC" assert cipher.encrypt("abc", -1) == "ZAB"
def test_decrypt_encrypt_letters_and_spaces_large_negative_success(): raw_string = "ALPHABETLEAHGEAIHGETT E RS" rotation_amount = -23849 encrypted_word = cipher.encrypt(raw_string, rotation_amount) decrypted_word = cipher.decrypt(encrypted_word, rotation_amount) assert decrypted_word == raw_string
# 'break_password' initialized as an empty list to receive appends break_password = [] # 'encypted_password' receives the new password one character at a time encrypted_password = '' # individual characters in 'password' are received and appended into 'break_password' list for character in lower_password: break_password.append(character) # test different strings # print(break_password) # individual indices of 'break_password' are iterated over to encrypt password for index in range(len(break_password)): break_password[index] = encrypt(break_password[index]) # takes individual list values and combines them into one string 'encrypted_password' for character in break_password: encrypted_password = encrypted_password + character # uses module pyperclip to copy 'encrypted_password' to user clipboard pyperclip.copy(encrypted_password) # informs user that 'encrypted password' has been copied to the user clipboard. print('The encrypted password has been copied to your clipboard.') loop = input('Would you like to enter another password to encrypt? -- (Y/N): ') if loop == 'Y': continue else: break
def test_encrypt_success_with_spaces(): assert cipher.encrypt("a bc", 1) == "B CD"
def encrypt(blob): if cipher and crypt_key: return '1' + cipher.encrypt(blob) return '0' + blob
def encrypt(blob): if cipher and crypt_key: return "1" + cipher.encrypt(blob) return "0" + blob
def testvnc(server, port, password, timeout, verbose): try: ip = socket.gethostbyname(server) except socket.error as e: print "%s" % e return 4 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) s.connect((ip, port)) except socket.error as e: print "Cannot connect to %s:%d" % (ip, port) print "%s" % e return 4 print "Connected to %s:%d" % (server, port) # 11111 # first, the server sends its RFB version, 12 bytes # more than 12 bytes if too many failures try: data = s.recv(1024) except socket.error as e: print "%s" % e return 4 if verbose: print "Received [%d] version:\n%r" % (len(data), data) if len(data) > 12: return 5 if data == "RFB 003.003\n": version = 3 elif data == "RFB 003.007\n": version = 7 elif data == "RFB 003.008\n": version = 8 else: return 3 print "RFB Version: 3.%d" % version # 22222 # now, the client sends its RFB version, 12 bytes m = data if verbose: print "Sending [%d] version:\n%r" % (len(m), m) try: s.send(m) except socket.error as e: print "%s\n" % e return 4 # 33333 # now, the server sends the security type[s] # in version 3, the server deciDES the security type, 4 bytes # in version 3 using RealVNC, the server sends authentication type and challenge in one message, thus recv(4) # in version 7/8, the server sends a list of supported security types: number of security types of 1 byte followed by a list of security types of 1 byte each try: if version == 3: data = s.recv(4) else: data = s.recv(1024) except socket.error as e: print "%s" % e return 4 if verbose: print "Received [%d] security type[s]:\n%r" % (len(data), data) if version == 3: security_type = struct.unpack("!I", data)[0] # security type 0 == Invalid # security type 1 == None # security type 2 == VNC if security_type == 1: return 0 elif security_type != 2: return 3 else: number_of_security_types = struct.unpack("!B", data[0])[0] if verbose: print "Number of security types: %d" % number_of_security_types if number_of_security_types == 0: # no security types supported return 3 vnc_enabled = False for i in range(1, number_of_security_types + 1): if i >= len(data): # should not happen, but don't want to cause an exception break security_type = struct.unpack("!B", data[i])[0] # security type 1 = None # security type 2 = VNC # security type 16 = Tight # security type 18 = VNC # security type 19 = VeNCrypt # plus some more if security_type == 1: return 0 elif security_type == 2: vnc_enabled = True if not vnc_enabled: print "VNC security type not supported" return 3 # 44444 # now, the client selects the VNC (2) security type, 1 byte m = struct.pack("!B", 2) if verbose: print "Sending [%d] security type:\n%r" % (len(m), m) try: s.send(m) except socket.error as e: print "%s\n" % e return 4 # 55555 # now, the server sends the authentication challenge, 16 bytes try: data = s.recv(16) except socket.error as e: print "%s" % e return 4 challenge = struct.unpack("!16s", data)[0] # if verbose: # print "Received [%d] challenge:\n%r" % (len(challenge), challenge) # 66666 # now, the client sends the response, 16 bytes key = calc_key(password) # encrypt 'challenge' using DES with 'key' cipher = DES.new(key, DES.MODE_ECB) response = cipher.encrypt(challenge) #if verbose: # print "Sending [%d] response:\n%r" % (len(response), response) try: s.send(response) except socket.error as e: print "%s\n" % e return 4 # 77777 # last, the server sends an ok or fail # 0 == OK, 1 == failed try: data = s.recv(1024) except socket.error as e: print "%s" % e return 4 if verbose: print "Received [%d] security result:\n%r" % (len(data), data) if len(data) == 0: result = struct.unpack("!0s", data[0:4])[0] if result == 0: # good password return 1 elif result == 1: # bad password return 2 else: # protocol error return 3 else: result = struct.unpack("!I", data[0:4])[0] if result == 0: # good password return 1 elif result == 1: # bad password return 2 else: # protocol error return 3
def test_encrypt_decrypt(): message = u"this is totally a secret" cipher_text = cipher.encrypt(message) assert message == cipher.decrypt(cipher_text)
def test_decrypt_deciphers_encrypt_variable_key(s, i): assert decrypt(encrypt(s, i), i) == s
def test_decrypt_deciphers_encrypt_fixed_key(s): cipher = encrypt(s, 20) assert decrypt(cipher, 20) == s
def test_encrypt_fail(): with pytest.raises(TypeError): cipher.encrypt('abc', 'q')
import argparse import cipher import euclidean as euclid import geneticalgorithm as ga import numpy as np import random import sys # Global variables __plain_text = "this is some plain text" __key = "quacktim" __encrypted_text = cipher.encrypt(__plain_text, __key) __population = [ ['aaaaaaaa', -1], ['bbbbbbbb', -1], ['cccccccc', -1], ['dddddddd', -1], ['eeeeeeee', -1], ['ffffffff', -1], ] # End of global variables def main(): # Init parser parser = argparse.ArgumentParser() #
def test_decrypt_encrypt_output_success(): raw_string = "ALPHABETLETTERS" rotation_amount = 1 encrypted_word = cipher.encrypt(raw_string, rotation_amount) decrypted_word = cipher.decrypt(encrypted_word, rotation_amount) assert decrypted_word == raw_string