コード例 #1
0
ファイル: app.py プロジェクト: judowal/Secret-Ciphers
    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.")
コード例 #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
コード例 #3
0
ファイル: __init__.py プロジェクト: yws/ipmsg
    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
コード例 #4
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"
コード例 #5
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
コード例 #6
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()
コード例 #7
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))
コード例 #8
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!')
コード例 #9
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
コード例 #10
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
コード例 #11
0
ファイル: server.py プロジェクト: srafay/Shinra-Tensei
    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)
コード例 #12
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
コード例 #13
0
    def decrypt(self):
        pub_cube = self.db.get_user_data(self.login)[0]
        print("Give me your private key")
        try:
            key = int(input("> "))
        except Exception:
            return

        ct = [
            tuple(map(Cube.from_str, x)) for x in loads(
                b64decode(self.db.get_ciphercube(self.login).decode()))
        ]
        cipher = Cipher(pub_cube, key)

        print(f"Your decrypted data: {cipher.decrypt(ct).hex()}")
コード例 #14
0
def crack_code(messages, tolerance):
    """Attempts to crack the code starting with the first word in the (newly resorted
	by pattern uniqueness) message. Tolerance is introduced to account for words in the
	message that are not necessarily in the corpus. Tolerance is the number of message words we are allowed
	to ignore while mapping message words to corpus words. At first we tolerate none of these, because
	ideally all of the message words are common enough to be found in the corpus. If that fails,
	we try again but increase tolerance by one."""
    messages = sort_by_pattern_uniqueness(messages)
    code = Cipher()
    cipher_found = crack_word(code, messages, 0, tolerance)
    if cipher_found:
        return code
    elif tolerance < len(messages):
        return crack_code(messages, tolerance + 1)
    else:
        quit("Error: No cipher found.")
コード例 #15
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
 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)
コード例 #16
0
ファイル: manager.py プロジェクト: chromia/passstore
 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
コード例 #17
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}")
コード例 #18
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)
コード例 #19
0
ファイル: main.py プロジェクト: angelsenra/orphans
    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()
コード例 #20
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
    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
コード例 #21
0
ファイル: __init__.py プロジェクト: yws/ipmsg
    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
コード例 #22
0
def time():
    if request.method == "POST":

        key = request.form.get("key")
        plainText = request.form.get("plainText")

        if not key:
            return render_template("index.html")
        if not plainText:
            return render_template("index.html")
        if ' ' in key:
            return render_template("index.html")
        cipher_guy = Cipher()
        #    if len(key)!= 2:
        #       return render_template("index.html")

        ciphertext = cipher_guy.cipher(plainText, key)

        return ciphertext

    # Cipherguy().doingAlgorithem(plainText,key)

    return render_template("index.html")
コード例 #23
0
from cipher import Cipher

cipher = Cipher()
cipher.encrypt()
cipher.decrypt()
コード例 #24
0
ファイル: main.py プロジェクト: srafay/Shinra-Tensei
from cryptography.fernet import Fernet
from cipher import Cipher
key = Fernet.generate_key()


original_data = "some text"

cryptor_object = Cipher(key)
encrypted_data = cryptor_object.encrypt(original_data)
print(encrypted_data)
decrypted_data = cryptor_object.decrypt(encrypted_data)
print(decrypted_data)
コード例 #25
0
ファイル: manager.py プロジェクト: chromia/passstore
 def __init__(self, passphrase):
     self.cipher = Cipher(passphrase)
コード例 #26
0
 def test_encode_longer_text_with_trivial_key(self):
     c = Cipher('a', 'ab')
     self.assertEqual('ab', c.encode('ab'))
コード例 #27
0
        self.text = msg

    def tokenize_and_clean(self):
        return util.tokenize_and_clean(self.text)

    def decode(self, cipher):
        """Applies the given cipher to the encoded message."""
        def decode_c(cipher, c):
            if c.isalpha():
                if c.isupper():
                    return cipher.get(c.lower()).upper()
                else:
                    return cipher.get(c)
            else:
                return c

        return "".join([decode_c(cipher, c) for c in self.text])


# Unit Test
if __name__ == "__main__":
    msg = "Lkccz mzfca."
    mapping = {'a': 'd', 'k': 'e', 'l': 'h', \
        'c': 'l', 'z': 'o', 'f': 'r', 'm': 'w'}
    code = Cipher()
    code.mapping = mapping

    coded_message = message(msg)
    print("\nTokenize message:\n" + str(coded_message.tokenize_and_clean()) +
          "\n")
    print("Decipher message:\n" + coded_message.decode(code) + "\n")
コード例 #28
0
 def test_encode_empty_string(self):
     c = Cipher('a', '')
     self.assertEqual('', c.encode(''))
コード例 #29
0
 def test_encode_if_shifted_character_overflows_alphabet(self):
     c = Cipher('b', 'ab')
     self.assertEqual('a', c.encode('b'))
コード例 #30
0
 def test_encode_longer_text_with_same_length_key(self):
     c = Cipher('ab', 'abc')
     self.assertEqual('ac', c.encode('ab'))