def __init__(self, host, port, conf_key, auth_key): crypt = Crypto() listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.bind( (host, int(port))) # this socket is bound to my port 9876 listen_socket.listen(1) # specify the "backlog" for this socket while True: # create the input list read_list = [listen_socket, sys.stdin] + self.connected_clients (ready_list, _, _) = select.select(read_list, [], []) for ready in ready_list: if ready is listen_socket: conn, addr = ready.accept() self.connected_clients += [conn] elif ready == sys.stdin: msg = sys.stdin.readline() msg = crypt.encrypt(msg, conf_key, auth_key) self.shout(listen_socket, msg) else: data = ready.recv(1024) if len(data) == 0: self.connected_clients.remove(ready) else: decrypt_data = crypt.decrypt(data, conf_key, auth_key) print(decrypt_data) self.shout(ready, decrypt_data.rstrip())
def get_entities(self): entities = [] data = { 'version':"", 'userName' : "", 'templateName' : "", 'resultDate' : "", 'resultRecall': "", 'resultTrace': "", 'resultTrack': "", 'resultRecreate': "" } try: objects = Therapy.all().order('userName').fetch(limit=None) if objects: for object in objects: data = { 'version': object.version, 'userName' : Crypto.decrypt(object.userName), 'templateName' : object.templateName, 'resultDate' : object.resultDate, 'resultRecall': Therapy.getData(object.resultRecall), 'resultTrace': Therapy.getData(object.resultTrace), 'resultTrack': Therapy.getData(object.resultTrack), 'resultRecreate': Therapy.getData(object.resultRecreate) } entities.append(data) except: result = {'status': "error", 'message': "Therapy data is not available" } return entities
def __init__(self, host, port, conf_key, auth_key): crypt = Crypto() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, int(port))) while True: # client has typed somethin [sys.stdin] # server sends a message [s] inputs = [sys.stdin, s] read, trash1, trash2 = select.select(inputs, [], []) for sock in read: if sock == s: # if sock is server, check for data data = sock.recv(1024) # write data to terminal decrypt_data = crypt.decrypt(data, conf_key, auth_key) print(decrypt_data) # otherwise client is trying to send a message else: # send server message msg = sys.stdin.readline() msg = crypt.encrypt(msg, conf_key, auth_key) s.send(msg)
def recover(self, bundleDir=DEFAULT_BUNDLE_DIR): """ Recover a secret from a bundle of encrypted shares. """ # Load the manifest files. shareManifest = ShareManifest.load(bundleDir) deviceManifest = DeviceManifest.load(bundleDir) # TODO: Verify the shareManifest contain the expected contents: k, n, etc shares = {} shareMatcher = identifyShares( sharesTable=shareManifest.shares, k=shareManifest.k) # Process k Yubikeys that match share files for coeff, sharefile, pkfp in shareMatcher: # Find the device so we can get it's PIN for decryption device = deviceManifest.findDevice(pubkeyFingerprint=pkfp) exitOnFail(device is not None, msg=f"Failed to find device in manifest file with " "pubkeyFingerprint={pkfp}") # Decrypt the sharenand store the result ok, result = Crypto.decrypt( ctxtfile=f"{bundleDir}/{sharefile}", pin=device["operationsPin"]) exitOnFail(ok) shares[coeff] = result # Recover the secret print(Crypto.recoverSecret(shares))
def get_therapydata(userName, templateName, resultDate): data = "" query = Therapy.all() cipher_text = Crypto.encrypt(userName) query.filter('userName ='******'templateName = ',templateName).filter('resultDate',resultDate).fetch(limit=None) object = query.get() if object: data = { 'userName' : Crypto.decrypt(object.userName), 'templateName' : object.templateName, 'resultDate' : object.resultDate, 'version': object.version, 'resultRecall': Therapy.getData(object.resultRecall), 'resultTrace': Therapy.getData(object.resultTrace), 'resultTrack': Therapy.getData(object.resultTrack), 'resultRecreate': Therapy.getData(object.resultRecreate) } result = {'status': "success", 'message': "Found therapy data", 'data': data} else: result = {'status': "error", 'message': "Data is not found.", 'data': ""} return result
def test_crypto2(self): a = "ATTACKATDAWN" c = Crypto("MANCHESTERBLUFF") b = c.encrypt(a) self.assertEqual(b, "MTGCJOSMHRXY") d = c.decrypt(b) self.assertEqual(d, "ATTACKATDAWN")
def test_crypto1(self): a = "teststringshowingnumbersdontwork123789$%!#" c = Crypto("MANCHESTERBLUFF") b = c.encrypt(a) self.assertEqual(b, "FEFVZXJBRXTSIBNZGAWTFWKWUPYNBTDKXNTUJLBPVH") d = c.decrypt(b) self.assertEqual(d, "TESTSTRINGSHOWINGNUMBERSDONTWORKKLMQRSXYUW")
def readtext(self): img = Image.open(str(self.img_obj)) passwd = self.read_text.text() steg = steganography.Steganography(img) msg = steg.decode_image() decr = Crypto(passwd, enc_msg=msg) end_msg = decr.decrypt() self.inserted_text.setText(end_msg)
class cryptoTestCase(unittest.TestCase): def setUp(self): self.crypto = Crypto() pt_bytes = bytes([i for i in range(97,97+16)]) #print(pt_bytes) self.pt = str(pt_bytes, encoding='utf-8') #print("self.pt = " + self.pt) def test_ecb(self): encryptd = self.crypto.encrypt(self.pt, AES.MODE_ECB) decryptd = self.crypto.decrypt(encryptd, AES.MODE_ECB) self.assertEqual(self.pt,decryptd) def test_cbc(self): encryptd = self.crypto.encrypt(self.pt, AES.MODE_CBC) decryptd = self.crypto.decrypt(encryptd, AES.MODE_CBC) self.assertEqual(self.pt,decryptd) def test_ctr(self): nonce = os.urandom(16) encryptd = self.crypto.encrypt(self.pt, AES.MODE_CTR, nonce) decryptd = self.crypto.decrypt(encryptd, AES.MODE_CTR, nonce) self.assertEqual(self.pt,decryptd)
def configMode(): run_values = {} with open('config.json', 'rb') as config: enc_bytes = config.read() while True: try: password = getpass.getpass( "Enter your password (No text will appear in console): ") break except Exception: continue crypto = Crypto(password) plaintext = crypto.decrypt(enc_bytes) dict = json.loads(plaintext) userObject = configDataFromDict(dict) #Populate run_values run_values['username'] = userObject.username run_values['password'] = userObject.password while True: try: symptoms = input("Are you feeling any symptoms?[Y/N]: ") if symptoms.upper() == 'Y': run_values['symptoms'] = True elif symptoms.upper() == 'N': run_values['symptoms'] = False break except Exception: continue return run_values
class Mongo: def __init__(self, config_path=None): if config_path is None: self.__config = Config() else: self.__config = Config(config_path) self.__host = self.__config.getValue('Mongo', 'HOST') self.__port = self.__config.getValue('Mongo', 'PORT') self.__cry = Crypto() self.__user = self.__cry.decrypt( self.__config.getValue('Mongo', 'USER')).decode("utf-8") self.__pass = self.__cry.decrypt( self.__config.getValue('Mongo', 'PASS')).decode("utf-8") self.__database = self.__config.getValue('Mongo', 'DATABASE') #connection_str="mongodb://"+self.__user+":"+self.__pass+"@"+self.__host+":"+self.__port+"/?authSource=admin" connection_str = "mongodb://" + self.__user + ":" + self.__pass + "@" + self.__host + ":" + self.__port + "/" + self.__database self.__client = MongoClient(connection_str, maxPoolSize=200, waitQueueTimeoutMS=100) self.__db = None def getDB(self, database): self.__db = self.__client[database] return self.__db def getCollection(self, collection): if self.__db is None: self.getDB(self.__database) self.__collection = self.__db[collection] return self.__collection def insert(self, record, collection): if not isinstance(record, list): raise TeleException(Type.WrongTypeException,'record should be list') self.getCollection(collection) return self.__collection.insert_many(record).inserted_ids def find(self, collection, condition=None): if condition is not None and not isinstance(condition, dict): raise TeleException(Type.WrongTypeException,'condition should be dict type') self.getCollection(collection) if condition is None: return list(self.__collection.find()) else: return list(self.__collection.find(condition)) def findSkipLimit(self, collection, skip, limit, condition=None): if condition is not None and not isinstance(condition, dict): raise TeleException(Type.WrongTypeException,'condition should be dict type') self.getCollection(collection) if condition is None: return list(self.__collection.find().skip(skip).limit(limit).sort('time',-1)) else: return list(self.__collection.find(condition).skip(skip).limit(limit)) def count(self,collection,condition=None): if condition is not None and not isinstance(condition, dict): raise TeleException(Type.WrongTypeException,'condition should be dict type') self.getCollection(collection) if condition is None: return self.__collection.find().count() else: return self.__collection.find(condition).count() def exist(self, condition, collection): if not isinstance(condition, dict): raise TeleException(Type.WrongTypeException,'condition should be dict type') self.getCollection(collection) return True if self.__collection.count(condition) > 0 else False def update(self, condition, update, collection): if not isinstance(condition, dict): raise TeleException(Type.WrongTypeException,'condition should be dict') if not isinstance(update, dict): raise TeleException(Type.WrongTypeException,'update should be dict') self.getCollection(collection) return self.__collection.update_many(condition, update) def saveUpdate(self, condition, update, collection): if not isinstance(condition, dict): raise TeleException(Type.WrongTypeException,'condition should be dict') if not isinstance(update, dict): raise TeleException(Type.WrongTypeException,'update should be dict') self.getCollection(collection) return self.__collection.update_many(condition, update, True) def saveUpdateOne(self, condition, update, collection): if not isinstance(condition, dict): raise TeleException(Type.WrongTypeException,'condition should be dict') if not isinstance(update, dict): raise TeleException(Type.WrongTypeException,'update should be dict') self.getCollection(collection) return self.__collection.update_one(condition, update, True) def deleteMany(self, idList, collection): if not isinstance(idList, list): raise TeleException(Type.WrongTypeException,'idList should be list') self.getCollection(collection) for obj in idList: self.__collection.delete_one({'_id': ObjectId(obj)})
break msg_bitlist = msg_bitlist[:length] message = self.bit_to_msg(msg_bitlist) return message if __name__ == '__main__': from crypto import Crypto message = 'asfdhfgjhgfyujh' cr1 = Crypto('pass', msg=message) enc_mess = cr1.encrypt() #print(enc_mess) img = Image.open('before.bmp') steg = Steganography(img, message=enc_mess) img_encoded = steg.encode_image() if img_encoded: img_encoded.save('after.bmp') print('Saved!') img2 = Image.open('after.bmp') steg2 = Steganography(img2) encoded_text = steg2.decode_image() #print(encoded_text) cr2 = Crypto('pass', enc_msg=encoded_text) print(cr2.decrypt()) #print(normal)
def decrypt(self, ctxtfile): ok, result = Crypto.decrypt(ctxtfile, pin="685828") if ok: print(f"Recovered: '{result}'") else: print(f"ERROR: {result}")
def test_decrypt_jgnnq_is_hello_in_two_shift(self): enc = Crypto(2, "jgnnq") self.assertEqual(enc.decrypt(), "hello")
def test_decrypt_b_is_z_in_two_shift(self): enc = Crypto(2, "b") self.assertEqual(enc.decrypt(), "z")
def test_decrypt_b_is_a_in_one_shift(self): enc = Crypto(1, "b") self.assertEqual(enc.decrypt(), "a")