Esempio n. 1
1
  def display(self):
    data = ""
    ct = shared.breaklines(Cipher.encrypt(self.cipher), self.maxlinelen).split("n")
    pt = shared.breaklines(self.cipher.decrypt(), self.maxlinelen).split("n")

    for index in range(len(ct)):
      data += ct[index] + "n"
      data += pt[index] + "nn"
    print data.strip("n")
Esempio n. 2
0
    def send(self, msg):
        serverKey = self.__establishConnection()
        cipher = Cipher(serverKey)

        if serverKey is None:
            self.socket.send('Goodbye')
            return self.__close()
        else:
            encryptedSessionKey = self.__getSessionKey(cipher)
            self.socket.send(encryptedSessionKey)
            encryptedData = self.socket.recv(1024)
            decryptedData = cipher.decrypt(encryptedData)
            if decryptedData != 'session cipher key acknowledged':
                self.socket.send('Goodbye')
                return self.__close()

        print('Client/Server acknowledgement successful!')

        encryptedMsg = cipher.encrypt(msg)
        self.socket.send(encryptedMsg)

        encryptedData = self.socket.recv(1024)
        decryptedData = cipher.decrypt(encryptedData)

        self.__close()
        return decryptedData
Esempio n. 3
0
    def encrypt(self, msg, addr):
        logger.debug('before encryption')
        if not self.knows(addr):
            logger.debug('dont know who')
            return False, None

        logger.debug('checking methods')
        methods = self.get_methods(shex(self.contact_capa[addr]))
        if None in methods:
            logger.debug('dont have methods')
            return False, None

        rsa_tag, cipher_tag = methods
        logger.debug('methods checked: rsa_tag=%s, cipher_tag=%s' % (rsa_tag, cipher_tag))

        try:
            rsa_key = self.contact_keys[addr][RSALEN[rsa_tag]]
        except KeyError:
            logger.debug('does not have public key for %s, %s' % (repr(addr), RSALEN[rsa_tag]))
            return False, None

        logger.debug('got rsa key %s' % (RSALEN[rsa_tag]))
        cipher = Cipher(*CIPHERS[cipher_tag])
        logger.debug('ready to encypt cipher')
        enc_msg = cipher.encrypt(msg)
        enc_ses_key = rsa_key.encrypt(cipher.session_key)

        capa = shex(rsa_tag | cipher_tag)
        enc_raw = capa + ':' + binascii.b2a_hex(enc_ses_key) + ':' + binascii.b2a_hex(enc_msg)

        logger.debug('encryption ok')
        return True, enc_raw
Esempio n. 4
0
 def set_deterministic(self, km=None):
     if km is None:
         pub = Cipher.get_public_key(self)
         i = random.randrange(2, pub["p"] - 1)
         km = pow(pub["beta"], i, pub["p"])
     Cipher.add_to_public_key(self, "km", km)
     return km
Esempio n. 5
0
def code(args: argparse.Namespace) -> None:
    if not hasattr(args, 'code'):
        print("Enter something to do: encode, decode, train, hack")
        sys.exit()

    if args.code in ('encode', 'decode'):
        text = fileread(args.input_file)
        cipher = Cipher()
        if args.cipher == 'caesar':
            try:
                key_int = int(args.key)
            except ValueError:
                print("Key for caesar should be integer")
                sys.exit()
            cipher = Caesar()
            cipher.key = key_int
        elif args.cipher == 'vigenere':
            cipher = Vigenere()
            cipher.key = args.key
        elif args.cipher == 'vernam':
            cipher = Vernam()
            cipher.key = args.key
        else:
            print("No such cipher type")
            sys.exit()
        if args.code == 'encode':
            textprint(args.output_file, cipher.encode(text))
        else:
            textprint(args.output_file, cipher.decode(text))
    elif args.code == 'train':
        FreqAnalysis(args.model_file).train(fileread(args.text_file))
    elif args.code == 'hack':
        text = fileread(args.input_file)
        textprint(args.output_file, FreqAnalysis(args.model_file).hack(text))
Esempio n. 6
0
 def _init_variables(self):
     self.exclude_extensions = [
         # 过滤某些特殊后缀的文件名
         "py",
         "gz",
         "rar",
         "ini",
         "nii",
     ]
     self.exclude_filenames = [
         ".DS_Store",
         "VERSION",
     ]
     # 全局的一个秘钥串
     self.secret_seed = ""
     self.checksmap = {
         "PatientID": False,
         "PatientName": False,
         "PatientBirthDate": False,
         "PatientSex": False,
         "InstitutionName": False,
         # "PatientAddress": True,
         # "PatientTelephoneNumbers": True,
     }
     self.PREFIX = "Anonymous_"
     self.cipher = Cipher()
     self.CIPHER_METHOD_ENCRYPT = "encrypt"
     self.CIPHER_METHOD_DECRYPT = "decrypt"
     self.DCM_EXTENSION = ".dcm"
Esempio n. 7
0
    def string_check(self, string):
        """ accepts a string to be checked for decryption/encryption eligibility, calls crypter() if eligible """
        # if self.functionality is set to "1"
        if self.functionality == "1":
            # if string contains only letters and spaces
            if all(x.isalpha() or x.isspace() for x in string):
                # sets self.message to string
                self.message = string

                # calls function that encrypts or decrypts messages
                self.crypter()

            # if string contains characters other than letters and spaces
            else:
                # prompt the user to enter a string containing only letters and spaces
                print(
                    "\nPlease enter a string containing only letters and spaces."
                )

        # if self.functionality is set to "2"
        elif self.functionality == "2":
            # if string contains only letters, spaces, space_chars, or pad_chars
            if all(x.isalpha() or x.isspace() or x in Cipher().space_chars
                   or x in Cipher().pad_chars for x in string):
                # sets self.message to string
                self.message = string

                # calls function that encrypts or decrypts messages
                self.crypter()

            # if string contains characters that cannot be decrypted
            else:
                # prompt the user to enter a valid string to be decrypted
                print("\nPlease enter a valid string to be decrypted.")
Esempio n. 8
0
    def encrypt(self, msg, addr):
        logger.debug('before encryption')
        if not self.knows(addr):
            logger.debug('dont know who')
            return False, None

        logger.debug('checking methods')
        methods = self.get_methods(shex(self.contact_capa[addr]))
        if None in methods:
            logger.debug('dont have methods')
            return False, None

        rsa_tag, cipher_tag = methods
        logger.debug('methods checked: rsa_tag=%s, cipher_tag=%s' %
                     (rsa_tag, cipher_tag))

        try:
            rsa_key = self.contact_keys[addr][RSALEN[rsa_tag]]
        except KeyError:
            logger.debug('does not have public key for %s, %s' %
                         (repr(addr), RSALEN[rsa_tag]))
            return False, None

        logger.debug('got rsa key %s' % (RSALEN[rsa_tag]))
        cipher = Cipher(*CIPHERS[cipher_tag])
        logger.debug('ready to encypt cipher')
        enc_msg = cipher.encrypt(msg)
        enc_ses_key = rsa_key.encrypt(cipher.session_key)

        capa = shex(rsa_tag | cipher_tag)
        enc_raw = capa + ':' + binascii.b2a_hex(
            enc_ses_key) + ':' + binascii.b2a_hex(enc_msg)

        logger.debug('encryption ok')
        return True, enc_raw
Esempio n. 9
0
class Server:
    name = 'Server1'
    publicKey = 'public_key123456'
    port = 9500

    def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = socket.gethostname()
        self.socket.bind((host, Server.port))
        self.cipher = Cipher(Server.publicKey)

    def __del__(self):
        self._close()

    def __decrypt(self, cipherText):
        return self.cipher.decrypt(cipherText)

    def listen(self):
        self.socket.listen(5)
        conn, addr = self.socket.accept()
        print( 'Connected by {}'.format(addr))

        # send server name
        conn.send(Server.name)

        # receive session cipher key
        encryptedSessionCipherKey = conn.recv(1024)
        sessionCipherKey = self.__decrypt(encryptedSessionCipherKey)

        if sessionCipherKey == 'session cipher key':
            conn.send(self.cipher.encrypt('session cipher key acknowledged'))
        else: 
            conn.send('Goodbye')
            conn.close()

        while True:
            encryptedData = conn.recv(1024)
            if not encryptedData: break
            decryptedData = self.__decrypt(encryptedData)
            if decryptedData == b'Hello':
                conn.send(self.cipher.encrypt('Hi'))
            else:
                conn.send(self.cipher.encrypt('Goodbye'))

        conn.close()
        # self.listen()

    def _close(self):
        self.socket.close()
Esempio n. 10
0
def apply_rules(file_path, password):
    lp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    lp_socket.connect(('127.0.0.1', 55430))
    encrypted_msg = Cipher(password).encrypt("RULE_FILE:" + file_path)
    final_msg = "UPDATE_RULES" + str(encrypted_msg)
    lp_socket.sendall(final_msg.encode('UTF-8'))
    lp_socket.close()
Esempio n. 11
0
	def encrypt(self,m):
		if type(m) == str:
			m = int(m)
			
		assert Aux.is_int(m)

		pub = Cipher.get_public_key(self)
		assert pub.has_key("n")
		assert pub.has_key("g")

		n = pub["n"]
		n2 = n*n if not pub.has_key("n2") else pub["n2"]
		if not pub.has_key("n2"):
			pub["n2"] = n2
		g = pub["g"]
		r = pub["r"] if pub.has_key("r") else random.randrange(1,n)

		assert abs(m) < n		

		if m < 0:
			g_m__n2 = self.__modinv(pow(g,-m,n2),n2)
		else:
			g_m__n2 = pow(g,m,n2)

		c = g_m__n2*pow(r,n,n2) % n2
		return str(c)
Esempio n. 12
0
 def test_cipher_random_key(self):
     c = Cipher()
     self.assertTrue(
         len(c.key) >= 100,
         'A random key must be generated when no key is given!')
     self.assertTrue(c.key.islower() and c.key.isalpha(),
                     'All items in the key must be chars and lowercase!')
Esempio n. 13
0
    def encrypt(self, m):
        assert self.__is_int(m)

        pub = Cipher.get_public_key(self)

        assert "p" in pub
        assert "alpha" in pub
        assert "beta" in pub

        p = pub["p"]
        alpha = pub["alpha"]
        beta = pub["beta"]
        km = pub["km"] if "km" in pub else None

        if self.exponential_mode:
            if m < 0:
                x = self.__modinv(pow(alpha, -m, p), p)
            else:
                x = pow(alpha, m, p)
        else:
            x = m

        if not km:
            i = randrange(2, p - 1)
            ke = pow(alpha, i, p)
            km = pow(beta, i, p)

            c = (x * km) % p
            return c, ke
        else:
            c = (x * km) % p
            return c
Esempio n. 14
0
class SecureSocket(object):

    def __init__(self, loop: asyncio.AbstractEventLoop, pub_key_path: str, pri_key_path: str, pub_key_path2: str):
        self.loop = loop or asyncio.get_event_loop()
        self.cipher = Cipher(pub_key_path, pri_key_path, pub_key_path2)

    async def decodeRead(self, conn: Connection):
        data = await self.loop.sock_recv(conn, BUFFER_SIZE)
        bs = bytes(data)
        ba = bytearray(self.cipher.decode(bs))
        print('%s:%d decodeRead %r', *conn.getsockname(), ba)
        return ba

    async def encodeWrite(self, conn: Connection, bs: bytearray):
        print('%s:%d encodeWrite %s', *conn.getsockname(), bytearray(bs))
        bs = bs.copy()
        bs = self.cipher.encode(bs)
        await self.loop.sock_sendall(conn, bs)

    async def encodeCopy(self, dst: Connection, src: Connection):
        """
        It encodes the data flow from the src and sends to dst.
        """
        print('encodeCopy %s:%d => %s:%d',
              *src.getsockname(), *dst.getsockname())

        while True:
            data = await self.loop.sock_recv(src, BUFFER_SIZE)
            if not data:
                break

            await self.encodeWrite(dst, bytearray(data))

    async def decodeCopy(self, dst: Connection, src: Connection):
        """
        It decodes the data flow from the src and sends to dst.
        """
        print('decodeCopy %s:%d => %s:%d',
              *src.getsockname(), *dst.getsockname())
        while True:
            bs = await self.decodeRead(src)
            if not bs:
                break

            await self.loop.sock_sendall(dst, bs)
Esempio n. 15
0
 def decrypt(self, data, ciphername='aes-256-cbc'):
     """
     Decrypt data with ECIES method using the local private key
     """
     blocksize = OpenSSL.get_cipher(ciphername).get_blocksize()
     iv = data[:blocksize]
     i = blocksize
     _, pubkey_x, pubkey_y, i2 = ECC._decode_pubkey(data[i:])
     i += i2
     ciphertext = data[i:len(data) - 32]
     i += len(ciphertext)
     mac = data[i:]
     key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
     key_e, key_m = key[:32], key[32:]
     if not equals(hmac_sha256(key_m, data[:len(data) - 32]), mac):
         raise RuntimeError("Fail to verify data")
     ctx = Cipher(key_e, iv, 0, ciphername)
     return ctx.ciphering(ciphertext)
Esempio n. 16
0
    def get_line_state(self, line_id):

        template_str = Template(UPDATE_LINE_STATE_URL)
        url = template_str.substitute(line_id=line_id)
        now = int(time.time())
        HEADERS["TIME"] = "%d" % now
        key = "%s%s%s%d" % (SECRET_KEY, PLAT_FROM, CID, now)
        token = self.get_token(key)
        HEADERS["ABTOKEN"] = token
        self._session.headers.update(HEADERS)

        response = self._session.get(url)
        if response.status_code != 200:
            print "%s return %d" % (url, response.status_code)
            return None

        ret_json = response.json()["root"]
        if ret_json["status"] != "200":
            print "%s return status = %s, message = %s" % (
                url, ret_json["status"], ret_json["message"])
            return None

        # bus_num = ret_json['num']
        bus_data = ret_json['data']['bus']
        buses = {}
        for bus in bus_data:
            key = 'aibang%s' % bus['gt']
            d = Cipher(key).decrypt

            # nextStationName = d(bus['ns'])
            next_station_num = int(d(bus['nsn']))
            next_station_distance = int(bus['nsd'])
            next_station_arriving_time = int(bus['nst'])
            # stationDistance = d(bus['sd'])
            # stationArrivingTime = d(bus['st'])
            lat = d(bus['x'])
            lon = d(bus['y'])

            # timeLocal = time.localtime(nextStationArrivingTime)
            # arrivingTimeStr = time.strftime("%H:%M", timeLocal)
            if next_station_distance > 0:
                station_id = next_station_num - 1
            else:
                station_id = next_station_num

            thisBus = {
                'nsd': next_station_distance,
                'nst': next_station_arriving_time,
                'x': lat,
                'y': lon
            }
            if buses.has_key(station_id):
                buses[station_id].append(thisBus)
            else:
                buses[station_id] = [thisBus]
        return buses
Esempio n. 17
0
    def decrypt(self, x):
        pub = Cipher.get_public_key(self)
        priv = Cipher.get_private_key(self)

        assert "p" in pub
        assert "d" in priv

        p = pub["p"]
        d = priv["d"]
        if (type(x) == list or type(x) == tuple) and len(x) == 2:
            c = x[0]
            ke = x[1]
        else:
            c = x
        km = pub["km"] if "km" in pub else pow(ke, d, p)

        inv = self.__modinv(km, p)

        return c * inv % p
Esempio n. 18
0
    def encrypt(self, message):
        """Encryption for Atbash:
        Maps letter in alphabet to its reverse.
        """
        encryption = {
            letter1: letter2
            for letter1, letter2 in zip(self.alphabet, self.alphabet[::-1])
        }
        encrypted_mess = []
        for letter in message:
            if letter in encryption.keys():
                for key, value in encryption.items():
                    if letter == key:
                        encrypted_mess.append(value)
            else:
                encrypted_mess.append(random.choice(self.spaces))
        encrypted_mess = "".join(encrypted_mess)

        Cipher.block_code(self, encrypted_mess)
Esempio n. 19
0
	def decrypt(self,c):
		assert Aux.is_int(c)
		c = long(c)	

		pub = Cipher.get_public_key(self)
		priv = Cipher.get_private_key(self)

		assert pub.has_key('n')
		assert pub.has_key('g')
		assert priv.has_key('lambda')

		n = pub['n']
		n2 = n*n if not pub.has_key("n2") else pub["n2"]
		g = pub['g']
		l = priv['lambda']
		mi = pow(l,l-1,n)

		charmical_function = lambda u,n: (u-1)/n
		m = charmical_function(pow(c,l,n2),n)*mi % n
		return m
Esempio n. 20
0
    def generate_lookup_table(self, a=0, b=10**3):
        pub = Cipher.get_public_key(self)

        alpha = pub["alpha"]
        p = pub["p"]

        table = {}
        for i in xrange(a, b):
            c = pow(alpha, i, p)
            table[c] = i
        return table
Esempio n. 21
0
    def encrypt(self):
        pub_cube = self.db.get_user_data(self.login)[0]
        cipher = Cipher(pub_cube)

        print("Give me something to encrypt")
        data = input("> ")
        if not data:
            return
        try:
            data = bytes.fromhex(data)
        except Exception:
            return

        encrypted = b64encode(
            dumps([(c1.as_str(), c2.as_str())
                   for c1, c2 in cipher.encrypt(data)]).encode())
        self.db.set_ciphercube(self.login, encrypted)

        print(f"Your ciphercubes: {encrypted.decode()}")
        print(f"Your private key: {cipher.x}")
Esempio n. 22
0
 def update_password(self, newpass):
     # Save all data file again with new passphrase
     # Backup current data folder just in case
     if not self.backup():
         print('backup failed.')
         return False
     # Recreate cipher with new passphrase
     self.cipher = Cipher(newpass)
     # Encrypting all
     try:
         for file in self.files:
             if not self.filewrite(file.filepath, file.data):
                 raise Exception
     except:
         # Unfortunately there was a failed operation, so rollback everything
         if not self.rollback():
             pass  # umm...
         return False
     else:
         return True
Esempio n. 23
0
    def __init__(self, config_file=None, config_orig=None):
        if not config_file:
            config_file = "config.yaml"
        if not config_orig:
            config_orig = "config.yaml.sample"

        # load config
        self.config_file = config_file
        try:
            self.CONFIG = yaml.load(open(config_file, 'r'))
        except IOError:
            self.CONFIG = yaml.load(open(config_orig, 'r'))

        self.CONFIG_ORIG = dict(self.CONFIG)  # keep loaded copy for comparison

        # encryption cipher
        self.cipher = Cipher(self.CONFIG['key'])

        self.CONFIG['seed'] = self.get_seed()

        if self.CONFIG['addr'] is None:
            self.debug("Getting new address")
            self.get_addr()

        # if anything changed, it gets saved
        self.save()

        # fetch ip
        self.ip = None
        self.fetch()

        self.seed = self.CONFIG.get('seed', '')
        self.addr = self.CONFIG.get('addr', '')
        self.index = self.CONFIG.get('index', '')
        self.name = self.CONFIG.get('name', '')
        self.ns = self.CONFIG.get('ns', '')
        self.node = self.CONFIG.get('node', '')
        self.url = self.CONFIG.get('url', '')
        self.interval = self.CONFIG.get('interval', '')
        self.forced_interval = self.CONFIG.get('forced_interval', '')
        self.update_retries = self.CONFIG.get('update_retries', 3)
Esempio n. 24
0
    def __init__(self, master, **kw):
        tk.Frame.__init__(self, master, **kw)
        self.logPath = "Passwords log"
        self.cipher = Cipher(b"")

        self.pad = Pad(self, (4, 4),
                       width=200,
                       height=200,
                       takefocus=0,
                       bg="lime")
        self.click = tk.Button(self,
                               text="Click here",
                               command=self.start_pad,
                               takefocus=0)
        self.masterpass = InfoEntry(self, info="MASTERPASS")
        self.passwords = ScrollableFrame(self)
        self.passwords.canvas.config(height=1)
        self.new = tk.Button(self, text="New Password", command=self.add_pass)
        self.gmail = tk.Button(self, text="-> Gmail")
        self.open = tk.Button(self, text="OPEN", command=self._open)
        self.save = tk.Button(self, text="SAVE", command=self._save)

        self.pad.grid(column=0, row=0, sticky="NSEW")
        self.click.grid(column=0, row=1, sticky="NSEW")
        self.masterpass.grid(column=0,
                             row=2,
                             rowspan=2,
                             sticky="NSEW",
                             padx=10,
                             pady=10)
        self.passwords.grid(column=1,
                            columnspan=2,
                            row=0,
                            rowspan=2,
                            sticky="NSEW")
        self.new.grid(column=1, row=2, sticky="NSEW")
        self.open.grid(column=2, row=2, sticky="NSEW")
        self.gmail.grid(column=1, row=3, sticky="NSEW")
        self.save.grid(column=2, row=3, sticky="NSEW")

        self.add_pass()
Esempio n. 25
0
    def decrypt(self, raw):
        enc_capa, enc_session_key, enc_msg = re.split(':', raw, 2)

        rsa_tag, cipher_tag = self.get_methods(enc_capa)
        if not rsa_tag or not cipher_tag:
            logger.debug('no method specified: %s, %s' % (rsa_tag, cipher_tag))
            return False, None

        try:
            key = self.key[RSALEN[rsa_tag]]
            enc_session_key = binascii.a2b_hex(enc_session_key)
            session_key = key.decrypt(enc_session_key)
        except:
            logger.debug(traceback.format_exc())
            return False, None

        cipher = Cipher(*CIPHERS[cipher_tag], session_key=session_key)
        enc_msg = binascii.a2b_hex(enc_msg)
        dec_msg = cipher.decrypt(enc_msg)

        return True, dec_msg
Esempio n. 26
0
    def decrypt(self, raw):
        enc_capa, enc_session_key, enc_msg = re.split(':', raw, 2)

        rsa_tag, cipher_tag = self.get_methods(enc_capa)
        if not rsa_tag or not cipher_tag:
            logger.debug('no method specified: %s, %s' % (rsa_tag, cipher_tag))
            return False, None

        try:
            key = self.key[RSALEN[rsa_tag]]
            enc_session_key = binascii.a2b_hex(enc_session_key)
            session_key = key.decrypt(enc_session_key)
        except:
            logger.debug(traceback.format_exc())
            return False, None

        cipher = Cipher(*CIPHERS[cipher_tag], session_key=session_key)
        enc_msg = binascii.a2b_hex(enc_msg)
        dec_msg = cipher.decrypt(enc_msg)

        return True, dec_msg
Esempio n. 27
0
    def raw_encrypt(
        data,
        pubkey_x,
        pubkey_y,
        curve='sect283r1',
        ephemcurve=None,
        ciphername='aes-256-cbc',
    ):  # pylint: disable=too-many-arguments
        """ECHD encryption, keys supplied in binary data format"""

        if ephemcurve is None:
            ephemcurve = curve
        ephem = ECC(curve=ephemcurve)
        key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
        key_e, key_m = key[:32], key[32:]
        pubkey = ephem.get_pubkey()
        iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize())
        ctx = Cipher(key_e, iv, 1, ciphername)
        ciphertext = iv + pubkey + ctx.ciphering(data)
        mac = hmac_sha256(key_m, ciphertext)
        return ciphertext + mac
Esempio n. 28
0
    def _acceptConnecton(self):
        print("[Server] Server to accept the new connection")
        conn, addr = self.socket.accept()
        encryptor = Cipher(self.public_key)
        with conn:
            while True:
                # always listen for incoming messages.
                data = conn.recv(1024)
                # Check if client is asking for server name
                if data == b'get_server_name':
                    # Send servers name to client
                    print("[Server] Sending server name to client")
                    self._sendMessage(conn, self.server_name)
                # Check if client is closing its connection with the server
                elif data == b'shutting_down':
                    # Remove client from trusted list
                    print("[Server] Client closing the connection")
                    self.trusted_clients.remove(self.get_client_address(addr))
                    # Drop connection with current client and start listening for new ones
                    self.listen(False)
                else:
                    # Check if client already has sent valid cipher key and is now transferring data
                    if self.get_client_address(addr) in self.trusted_clients:
                        if data:
                            # Client is transferring data right now
                            print("[Server] Message from client: " +
                                  encryptor.decrypt(data.decode()).decode())
                            ack_message = "OK"
                            self._sendMessage(
                                conn,
                                encryptor.encrypt(ack_message).decode())
                    # Lets see if client sent us valid cipher key phrase
                    elif encryptor.decrypt(
                            data.decode()) == b'session cipher key':
                        client_address = self.get_client_address(addr)
                        # Prepare acknowledgment message for client
                        ack_message = "session cipher key acknowledgement"
                        # Mark this client trusted
                        self.trusted_clients.append(client_address)
                        print("[Server] Client sent valid session cipher key")
                        # Send acknowledgment message to client
                        self._sendMessage(
                            conn,
                            encryptor.encrypt(ack_message).decode())

                    else:
                        # Client has provided invalid session cipher key
                        ack_message = "Invalid session cipher key"
                        print(
                            "[Server] Client sent invalid session cipher key")
                        self._sendMessage(
                            conn,
                            encryptor.encrypt(ack_message).decode())
                        # Drop connection with current client and start listening for new ones
                        self.listen(False)
Esempio n. 29
0
def attempt_match(code, messages, i, wordb, tolerance):
    """Explores a corpus-word pair for the current message word. batch keeps track of which
	new letters are mapped under the assumption that wordb is a match for the ith message word."""
    batch = Cipher()
    worda = messages[i]
    for chara, charb in zip(worda, wordb):
        """Checks if the new assumption would conflict with the current mapping. If it does,
		return False- i.e., try a different corpus word."""
        if not code.isCompatible(chara, charb) or not batch.isCompatible(
                chara, charb):
            return False
        elif not code.isMapped(chara) and not batch.isMapped(chara):
            batch.map(chara, charb)
    """If we get here, it means that this word mapping is 
	compatible with our cipher so far and also internally.
	Map the new batch of letters (from the current word) in the cipher.
	If we made a mistake, we can unmap it later when we return to this layer of
	the recursion."""
    code.map_batch(batch)
    """Check if we've reached the end of our message. 
	If so, we have found a complete compatible cipher. Otherwise,
	proceed to the next word."""
    if i >= len(messages) - 1:
        return True
    elif crack_word(code, messages, i + 1, tolerance):
        return True
    else:
        code.unmap_batch(batch)
        return False
Esempio n. 30
0
    def get_line_stations(self, line_id):

        template_str = Template(UPDATE_LINE_URL)
        url = template_str.substitute(line_id=line_id)

        now = int(time.time())
        HEADERS["TIME"] = "%d" % now
        key = "%s%s%s%d%s" % (SECRET_KEY, PLAT_FROM, CID, now, UPDATE_PATH)
        token = self.get_token(key)
        HEADERS["ABTOKEN"] = token

        self._session.headers.update(HEADERS)
        r = self._session.get(url)
        if r.status_code != 200:
            print "%s return %d" % (url, r.status_code)
            return None

        ret_json = r.json()
        if ret_json["errcode"] != "200":
            print "%s return errcode = %s, errmsg = %s" % (
                url, ret_json["errcode"], ret_json["errmsg"])
            return None
        if len(ret_json['busline']) > 1:
            print "warning have more than one busline"

        bus_line = ret_json['busline'][0]
        line_id = bus_line['lineid']

        cipher = Cipher('%s%s' % (CUSTOM, line_id))

        #路线坐标
        #coord = busLine['coord']

        base_info = ""
        line_name = cipher.decrypt(bus_line['linename'])
        if STD_OUT_ENCODING == "utf8" or STD_OUT_ENCODING == "utf-8":
            self.print_info(line_name)
        else:
            self.print_info(line_name.decode('utf-8'))
        base_info += "%s\n" % (line_name.decode("utf-8"))

        self.print_info("%s" % (bus_line['time']))
        base_info += "%s\n" % (bus_line['time'])

        ret_stations = []
        stations = bus_line['stations']['station']
        for station in stations:
            station_no = int(cipher.decrypt(station['no']))
            station_name = cipher.decrypt(station['name'])
            lon = cipher.decrypt(station['lon'])
            lat = cipher.decrypt(station['lat'])
            # self.print_info("%d %s %s %s" % (stationNo, stationName, lon, lat))
            ret_stations.append({
                'no': station_no,
                'name': station_name,
                'x': lon,
                "y": lat
            })
        return ret_stations, base_info
Esempio n. 31
0
    def decrypt(self, x):
        #
        # Decrypts a single integer
        #
        pub = Cipher.get_public_key(self)
        priv = Cipher.get_private_key(self)

        assert pub.has_key("p")
        assert priv.has_key("d")

        p = pub["p"]
        d = priv["d"]
        if type(x) == list and len(x) == 2:
            c = x[0]
            ke = x[1]
        else:
            c = x
        km = pub["km"] if pub.has_key("km") else pow(ke, d, p)

        inv = self.__modinv(km, p)

        return c * inv % p
Esempio n. 32
0
    def __init__(self, config):
        self.local_addr = config["local_addr"]
        config["local_port"] = int(config["local_port"])
        self.local_port = config["local_port"]

        self.local_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.local_socket.bind((self.local_addr, self.local_port))
        self.local_socket.listen(1024)
        print('Listening at {}:{}'.format(self.local_addr, self.local_port))

        self.cipher = Cipher(config['key'])
        self.config = config
        self.config['cipher'] = self.cipher
        self.config["is_client"] = False
Esempio n. 33
0
	def h_operation(self,a,b,mod=None,fix=None):
		assert Aux.is_int(a)
		assert Aux.is_int(b)
		a = long(a)	
		b = long(b)	

		if mod is None:
			mod = Cipher.get_public_key(self)["n2"]
		if fix is None:
			c = a*b % mod
		else:
			c = a*b*fix % mod

		return str(c)
 def test_cipher_encode3(self):
     c = Cipher('dddddddddddddddddddddd')
     self.assertEqual('yhqlylglylfl', c.encode('venividivici'))
Esempio n. 35
0
 def __init__(self):
   Cipher.__init__(self)
   self.ctkey = string.ascii_uppercase
   self.ptkey = "-" * 26
   self.decrypt_filter = lambda char: char in (string.ascii_letters + string.punctuation + " ")
   self.encrypt_filter = self.decrypt_filter
 def test_cipher_compositiion2(self):
     plaintext = 'adaywithoutlaughterisadaywasted'
     c = Cipher()
     self.assertEqual(plaintext, c.decode(c.encode(plaintext)))
 def test_cipher_compositiion1(self):
     key = ('duxrceqyaimciuucnelkeoxjhdyduucpmrxmaivacmybmsdrzwqxvbxsy'
            'gzsabdjmdjabeorttiwinfrpmpogvabiofqexnohrqu')
     plaintext = 'adaywithoutlaughterisadaywasted'
     c = Cipher(key)
     self.assertEqual(plaintext, c.decode(c.encode(plaintext)))
 def test_cipher_encode_short_key(self):
     c = Cipher('abcd')
     self.assertEqual('abcdabcd', c.encode('aaaaaaaa'))
 def test_cipher_encode4(self):
     key = ('duxrceqyaimciuucnelkeoxjhdyduucpmrxmaivacmybmsdrzwqxvbxsy'
            'gzsabdjmdjabeorttiwinfrpmpogvabiofqexnohrqu')
     c = Cipher(key)
     self.assertEqual('gccwkixcltycv', c.encode('diffiehellman'))
Esempio n. 40
0
from sys import argv
import re
import random
from cipher import Cipher
from ngram import NGram
from break_cipher import BreakCipher

script,enc,text = argv

c = Cipher()
textEnc = c.cipher(enc)

dictionary =  c.processText(text)

b = BreakCipher()

b.breakCipher(textEnc,dictionary)

 def test_cipher_encode2(self):
     c = Cipher('aaaaaaaaaaaaaaaaaaaaaa')
     self.assertEqual('itisawesomeprogramminginpython',
                      c.encode('itisawesomeprogramminginpython'))
Esempio n. 42
0
 def decrypt(self, text = ""):
   text = Cipher.decrypt(self, text)
   return self.process(self.ctkey, self.ptkey, text.upper())
Esempio n. 43
0
 def encrypt(self, text = ""):
   text = Cipher.encrypt(self, text)
   return self.process(self.ptkey, self.ctkey, text.lower())
Esempio n. 44
0
 def frequency_list(self, length = 1, text = ""):
   """Displays counts for frequencies of characters"""
   text = Cipher.encrypt(self.cipher, text)
   self.print_counts(shared.calc_graphs(text.split(" "), int(length)))
Esempio n. 45
0
 def frequency_list(self, length = 1, text = ""):
     text = Cipher.encrypt(self.cipher, text)
     self.print_counts(shared.calc_graphs(text, int(length)))