Beispiel #1
0
    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)
Beispiel #2
0
 def encrypt(self, pubkeyfile, ctxtfile):
   ok = Crypto.encrypt(
     plaintext="hello, world",
     pubkeyfile=pubkeyfile,
     ctxtfile=ctxtfile)
   if not ok:
     print(f"ERROR: during encryption")
Beispiel #3
0
 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
Beispiel #4
0
 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")
Beispiel #5
0
 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 __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())
Beispiel #7
0
 def update(userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate):
     query = Therapy.all()
     query.filter('userName ='******'templateName = ',templateName).filter('resultDate',resultDate).fetch(limit=None)
     object = query.get()
     if object:
         if object.resultRecall == resultRecall and object.resultTrace == resultTrace and object.resultTrack == resultTrack and object.resultRecreate == resultRecreate:
             return
         else:
             object.version = object.version + 1
             Therapy.add_version(object.version, userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate)
Beispiel #8
0
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)
Beispiel #9
0
 def add_version(version, userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate):
     try:
         entity = Therapy(
                 version=long(version),
                 userName=Crypto.encrypt(userName),
                 templateName=templateName,
                 resultDate=resultDate,
                 resultRecall=resultRecall,
                 resultTrace=resultTrace,
                 resultTrack=resultTrack,
                 resultRecreate=resultRecreate)
         entity.put()
     except:
         result = {'status': "error",
                'message': "Save of Therapy data is unsuccessful. Please try again."}
Beispiel #10
0
  def split(self, k, n, length=128, bundleDir=DEFAULT_BUNDLE_DIR):
    """
    Generate a new secret, split it into shares, encrypt them, and write 
    them in a bundle to a file.
    """
    # Verify cmd line arguments
    k, n = int(k), int(n)
    exitOnFail(k <= n, f"ERROR: K=({k}) cannot be larger than N(={n})")

    devices = DeviceManifest(bundleDir).devices()
    exitOnFail(n == len(devices), 
      f"ERROR: The total number of shares, N, must match the number of "
      "public keys enrolled. Instead found N={n}, number of pubkeys="
      "{len(pubkeyfiles)}")

    shares = Crypto.splitSecret(bits=length, k=k, n=n)

    # Store information about each encrypted share
    shareManifest = ShareManifest.new(directory=bundleDir, k=k, n=n)

    # Remove any existing sharefiles in the directory
    purgeSharefiles(bundleDir)

    # Encrypt each share under a distinct pubkey
    for (device, (coeff, share)) in zip(devices, shares.items()):
      # Grab the pubkey filename independent of the directory
      pubkeyFilename = device["pubkeyFilename"]

      # Encrypt the share and write it to a file
      sharefile = f"share-{coeff}.ctxt"
      ok = Crypto.encrypt(
        plaintext=share,
        certfile=f"{bundleDir}/{pubkeyFilename}", 
        ctxtfile=f"{bundleDir}/{sharefile}")
      exitOnFail(ok)

      shareManifest.addShare(
        coeff=coeff,
        encryptedShareFile=sharefile,
        pubkeyFilename=device["pubkeyFilename"],
        pubkeyFingerprint=device["pubkeyFingerprint"])

    # Write the share manifest file
    shareManifest.write()
Beispiel #11
0
    def InsertText(self):
        img = Image.open(str(self.img_obj))
        passwd = self.read_text.text()
        text = self.inserted_text.text()
        enc = Crypto(passwd, msg=text)
        enc_text = enc.encrypt()
        steg = steganography.Steganography(img, message=enc_text)

        path = str(self.img_obj)
        filename = path.split('/')
        fn = filename.pop()
        fn = 'enc_' + fn
        filename.append(fn)
        new_path = os.path.join(*filename)
        new_path = '/' + new_path
        img_enc = steg.encode_image()
        img_enc.save(new_path)

        self.select_file_after(new_path)
Beispiel #12
0
    def add(userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate):
        result = {}
        try:
            if userName != "":
                #Check if the therapy data is new data
                isNew = True
                object = Therapy.get_therapydata(userName, templateName, resultDate)
                if object['data'] != "":
                    isNew = False

                if isNew:
                    version = 0
                    entity = Therapy(
                                    version=long(version),
                                    userName=Crypto.encrypt(userName),
                                    templateName=templateName,
                                    resultDate=resultDate,
                                    resultRecall=resultRecall,
                                    resultTrace=resultTrace,
                                    resultTrack=resultTrack,
                                    resultRecreate=resultRecreate)
                    entity.put()
                    result={'status': "add successful",
                        'message': "Added new therapy data into Datastore: user name: " + userName + ", template name: " + templateName + ", result date: " + resultDate}
                else:
                    Therapy.update(userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate)
                    result={'status': "update successful",
                        'message': "Updated therapy data for user name: " + userName + ", template name: " + templateName + ", result date: " + resultDate}

            else:
              result = {'status': "error",
                        'message': "Please provide user name."}
        except:
            result = {'status': "error",
                   'message': "Save of Therapy data is unsuccessful. Please try again."}

        return result
Beispiel #13
0
    def test_encrypt_z_is_b_in_two_shift(self):
        enc = Crypto(2, "z")

        self.assertEqual(enc.encrypt(), "b")
Beispiel #14
0
    def test_encrypt_a_is_b_in_one_shift(self):
        enc = Crypto(1, "a")

        self.assertEqual(enc.encrypt(), "b")
Beispiel #15
0
    def test_encrypt_hello_is_jgnnq_in_two_shift(self):
        enc = Crypto(2, "hello")

        self.assertEqual(enc.encrypt(), "jgnnq")
Beispiel #16
0
	def save(self):
		crypto = Crypto(self._password)
		to_save = json.dumps(self.__dict__)
		with open("config.json", "wb") as config:
			config.write(crypto.encrypt(to_save.encode()))
Beispiel #17
0
                    break
            if index >= length:
                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())
Beispiel #18
0
 def testencryption(self):
     crypto = Crypto()
     print(">>>")
     print(crypto.encrypt('test'))
     print("<<<")