예제 #1
0
def hideFunc(SM, password, CM):
    encSM = encrypt(password, SM)
    print("Encrypted secret message going to send:", encSM)
    CM_HM = embedFunc(encSM, CM)
    print("Cover message=", CM_HM)
    py.copy(CM_HM)
    return CM_HM
예제 #2
0
    def login(self, account_name: str, password: str, addr):
        exist, info = self._search(account_name)

        if (exist == 0):
            return 'INVALID_ACCOUNT'
        else:
            print('[UIH.login()]', info)
            if len(info) != 1:
                return 'ERROR duplicated account name'
            else:
                userInfo = info[0]
                encrypted_password = encrypt(password)

                if encrypted_password == userInfo[2]:
                    print('[UIH.login()]', 'for loop')
                    for i, user in enumerate(self.online_table):
                        if user[1] == account_name:
                            if user[2] == False:
                                user_tmp = list(user)
                                user_tmp[2] = True
                                user_tmp[3] = addr
                                self.online_table[i] = tuple(user_tmp)
                                return 'SUCCESS'
                            else:
                                return 'REENTRY'
                else:
                    return 'WRONG_PW'
예제 #3
0
def Administrator(admin, ord, mykey):
    if ord[0] == 'create account':
        file = ord[1]
        path = os.getcwd() + '/' + file
        if not os.path.exists(path):
            os.makedirs(file)
            msg = ord[2]
            night = (encrypt(msg, mykey)).decode()
            sec = open(file + '/night.txt', 'w')
            sec.write(night)
            sec.close
            with open('user.txt', 'r') as data:
                new_users = (data.read()).strip()
                new_users = (new_users + file + ":" + ord[3] + ":")
                print(new_users, file=open('user.txt', 'w'))
            try:
                with open('admins_report.txt', 'a') as report:
                    report.write('New user was created {}: by {}:\n'.format(
                        file, admin))
                    msg = ("User {} was created by {} ".format(file, admin))
                    return msg
            except:
                msg = (
                    "Could not write a report for creating new account for but user was created{}"
                    .format(admin))
                return msg
        else:
            msg = (
                "Couldn't create a new user ! [issue] Name of the user may be already taken !"
            )
            return msg
    elif ord[0] == 'delete account':
        try:
            file = ord[1]
            path = os.getcwd() + '/' + file
            if os.path.exists(path):
                shutil.rmtree(path, ignore_errors=True)
                with open('admins_report.txt', 'a') as report:
                    report.write(
                        "A user was deleted by {} at [to use time here]\n".
                        format(admin))
                    msg = ("A user was deleted by {} at [to use time here]".
                           format(admin))  #use time
                    return msg
            else:
                msg = ("User may not be exists !")
                return msg
        except:
            msg = (
                "Couldn't Delete User please report the issue to the AnonyBox TM"
            )
            return msg
예제 #4
0
def send_data_impl(s1,s2,fileName,value,keyword1,keyword2,keyword3,keyword4,keyword5):
    s1.send('file'.encode('utf-8'))
    key=keygen('AES-128').decode('utf-8')
    print(key)
    keyword_list=[]
    if keyword1!='':
        keyword_list.append(keyword1)
    if keyword2!='':
        keyword_list.append(keyword2)
    if keyword3!='':
        keyword_list.append(keyword3)
    if keyword4!='':
        keyword_list.append(keyword4)
    if keyword5!='':
        keyword_list.append(keyword5)
    filesize_bytes = os.path.getsize(fileName) + 16
    dirc = {
        'filename': 'enc'+fileName[fileName.rfind("/",0,len(fileName))+1:],
        'filesize_bytes': filesize_bytes,
        'price': value,
        'keyword_len': str(len(keyword_list)),
    }
    head_info = json.dumps(dirc)
    head_info_len = struct.pack('i', len(head_info))
    s2.send(head_info_len)
    s2.send(head_info.encode('utf-8'))
    print(key_pres)
    for i in range(0,len(keyword_list)):
        cipherii, srecord = sch.Enc(key_pres.pubkey, key, keyword_list[i])
        hashtable[srecord.hc] = srecord.sid
        s2.send(str(cipherii).encode('utf-8'))
    iv=ivgen()
    print(iv)
    f=open(fileName,'rb')
    s2.send(iv)
    data=f.read(83886080)
    key=key.encode('utf-8')
    while data:
        cipher_data = encrypt(data,key,iv)
        print(len(cipher_data))
        s2.sendall(cipher_data)
        data=f.read(83886080)
    #s2.close()
    with open('filehash', 'a') as f:
        f.write(str(hashtable)+'\n')
예제 #5
0
    def register(self, account_name: str, password: str) -> str:
        exist, foo = self._search(account_name)

        if (exist == 0):
            encrypted_password = encrypt(password)

            tmp = (self.uid, account_name, encrypted_password)
            self.c.execute('INSERT INTO Users VALUES(?, ?, ?)', tmp)
            self.conn.commit()

            self.online_table.append(
                (self.uid, account_name, False, None, None, None, None))

            self.uid = self.uid + 1

            for i in self.online_table:
                print(i)

            return 'SUCCESS'

        else:
            #print('requested account name already exists!')
            return 'FAILED'
예제 #6
0
def main():
    print(ANSI_CYAN + "BETA [!]" + ANSI_RESET)
    global admin_stat
    global Nsec
    secure_flag = False
    #key = 'godisdead'
    port = 2468
    try:
        host = str(sys.argv[1])
        key = (sys.argv[2])
    except:
        print(
            'example : main.py 127.0.0.1 godisdead\n [python file name] [HOST][Night Key]'
        )
        sys.exit()
    print(ANSI_CYAN + "Using Key:{} Using :{} Port".format(key, port) +
          ANSI_RESET)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    s.listen(1)  # it will listen to only for one connection
    conn, addr = s.accept()
    #this is a beta it can handle only one connection and if the connection got closed the server will be down too
    with conn:
        print('Connection by {}'.format(addr))
        while True:
            ### note dont forget to send your public key so you can uncode the data
            #public_key = conn.recv(1024) # first ill recive a key from the client
            conn.send(
                b'Hello Guest, The connection is not encrypt yet...\nAlso you should have the Secret ;)\nEverything after this message will be encrypt...'
            )
            user = conn.recv(1024).decode()  # ill recive the user
            if len(user) > 0:
                conn.send(b'OK')
                night_secret = conn.recv(
                    1024).decode()  # ill recive the night secret here
                check = night_sec(user, night_secret, key)
                if check == 1:
                    secure_flag = True  # the user sent a valid night secret to do a secure connection with
                    msg = encrypt('OK', Nsec)
                    conn.send(msg)
                    secure_passd = conn.recv(1024).decode()
                    passd = decrypt(secure_passd, Nsec)
                    passd = passd.decode()
                    try:
                        info = user, passd
                        auth = authentication(info, key)
                        if admin_stat == True:
                            print("{} Loged in as Administrator ".format(auth))
                            msg = ('Welcome Administrator {}'.format(auth))
                            mesg = encrypt(msg, key)
                            conn.send(mesg)
                            while True:
                                stuff = conn.recv(1024)
                                ##stuff to do for admins
                                ord = decrypt(stuff, key)
                                ord = ord.decode()
                                if ord.find(":") != -1:
                                    ord = ord.split(':')
                                elif ord.find(":") == -1:
                                    pass
                                if type(ord) == list:
                                    try:
                                        if ord[0] == 'create account':
                                            if admin_stat == True:

                                                done = Administrator(
                                                    user, ord, key)
                                                msg = encrypt(done, key)
                                                conn.send(msg)
                                            else:
                                                msg = (
                                                    'You should have an Administrator privileges for that'
                                                )
                                                mesg = encrypt(msg, key)
                                                conn.send(mesg)
                                        elif ord[0] == 'send mail':
                                            try:
                                                done = normal_users(
                                                    user, ord
                                                )  #there is no need for the Administrator
                                                #privileges so normal_users will handle it"
                                                msg = encrypt(msg, key)
                                                conn.send(msg)
                                            except:
                                                msg = ('Unable to {}'.format(
                                                    ord[0]))
                                                mesg = encrypt(msg, key)
                                                conn.send(mesg)
                                        elif ord[0] == 'delete account':

                                            if admin_stat == True:
                                                done = Administrator(
                                                    user, ord, key)
                                                msg = encrypt(done, key)
                                                conn.send(mesg)

                                            else:

                                                try:
                                                    info = ord[1], ord[2]
                                                    checking_user = authentication(
                                                        info, key)
                                                    if checking_user == ord[1]:

                                                        done = normal_users(
                                                            user, ord)
                                                        conn.close(
                                                        )  #there is no need for telling the user we done just close the connection
                                                    else:
                                                        pass
                                                except:
                                                    msg = ('Unable to {}'.
                                                           format(ord))
                                                    mesg = encrypt(msg, key)
                                                    conn.send(mesg)
                                    except:
                                        print('error while handling the order')
                                elif type(ord) != list:
                                    if ord == "inbox":
                                        done = normal_users(user, ord)
                                        msg = encrypt(done, key)
                                        conn.send(msg)
                                else:
                                    msg = (
                                        'server could not understand your order {}'
                                        .format(ord))
                                    mesg = encrypt(msg, key)
                                    conn.send(mesg)
                        elif (admin_stat == False) and (auth != 0):
                            msg = ('Welcome {}'.format(auth))
                            mesg = encrypt(msg, key)
                            conn.send(mesg)
                            while True:
                                stuff = conn.recv(1024)
                                #stuff to do for users
                                ord = decrypt(stuff, key)
                                ord = ord.decode()
                                if ord.find(":") != -1:
                                    ord = ord.split(':')
                                elif ord.find(":") == -1:
                                    pass
                                if type(ord) == list:
                                    try:
                                        if ord[0] == 'create account':
                                            msg = (
                                                'You should have an Administrator privileges for that'
                                            )
                                            mesg = encrypt(msg, key)
                                            conn.send(mesg)
                                        elif ord[0] == 'send mail':
                                            try:
                                                done = normal_users(
                                                    user, ord
                                                )  #there is no need for the Administrator
                                                #privileges so normal_users will handle it"
                                                msg = encrypt(msg, key)
                                                conn.send(msg)
                                            except:
                                                msg = ('Unable to {}'.format(
                                                    ord[0]))
                                                mesg = encrypt(msg, key)
                                                conn.send(mesg)
                                        elif ord[0] == 'delete account':
                                            try:
                                                info = ord[1], ord[2]
                                                checking_user = authentication(
                                                    info, key)
                                                if checking_user == ord[1]:
                                                    done = normal_users(
                                                        user, ord)
                                                    conn.close(
                                                    )  #there is no need for telling the user we done just close the connection
                                                else:
                                                    pass
                                            except:
                                                msg = (
                                                    'Unable to {}'.format(ord))
                                                mesg = encrypt(msg, key)
                                                conn.send(mesg)
                                    except:
                                        print('error while handling the order')
                                elif type(ord) != list:
                                    if ord == "inbox":
                                        done = normal_users(user, ord)
                                        msg = encrypt(done, key)
                                        conn.send(msg)
                        else:
                            break  ## TODO: add a blocking ips
                    except:
                        print(
                            'there was an error while checking someone login {}'
                            .format(user))
                elif check == 3:
                    print('Could not open [{}] night secret'.format(user))
                    conn.send(b"we don't like you")
                    s.close()
                else:  #CONNECTION IS NOT SECURE AT ALL ADMIN SHOULD TAKE ACTION HERE
                    secure_flag = False
                    conn.send('NOT found').encode()
                    print(
                        'Uh no f**k you im out, there was no secure connection so i dropped it'
                    )
                    s.close()
                    #sys.exit()
            else:
                user = ''
                night_secret = ''
                print('user was not vaild')
                s.close()
예제 #7
0
def test_encrypt():
    assert convert_stream_to_plaintext(encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f")) == "69c4e0d86a7b0430d8cdb78070b4c55a"
예제 #8
0
def main():
    port = 2468
    host = str(sys.argv[1])
    print("Using {}:{} ".fromat(host,port))
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((host,port))
    try:
        wlc_msg = s.recv(1024).decode()
        print(wlc_msg)
        user = input('User :'******'OK':
            secret= input('Your secret :')
            night_secret = encrypt(secret,secret)
            s.send(night_secret)
            respon = s.recv(1024).decode()
            try:
                respon = decrypt(respon,secret).decode() 
                if respon == 'OK':
                    password = input('Password:'******':>')
                        try:
                            if len(cmd) < 1 :
                                cmd = input('Type something :>')
                        except:
                            pass
                        if cmd == 'help':
                            help()
                        elif cmd == 'create account':
                            username = input('account user:'******'Password for the user:'******'Night secret for the user:'******'create account'+':'+username+':'+user_night+':'+user_password)
                            command = encrypt(cmd,secret)
                            s.send(command)
                            s.settimeout(3.5)
                            server_resposn = s.recv(1024).decode()
                            server_resposn = decrypt(server_resposn,secret)
                            print(server_resposn.decode())
                        elif cmd == 'delete account':
                            username = input('account user:'******'Password:'******'delete account'+':'+username+':'+user_password)
                            command = encrypt(cmd,secret)
                            s.send(command)
                            s.settimeout(3.5)
                            server_resposn = s.recv(1024).decode()
                            server_resposn = decrypt(server_resposn,secret)
                            print(server_resposn)
                        elif cmd == 'inbox':
                            cmd = encrypt(cmd,secret)
                            s.send(cmd)
                            s.settimeout(3.5)
                            server_resposn = s.recv(1024).decode()
                            server_resposn = decrypt(server_resposn,secret)
                            print(server_resposn)
                        elif cmd == 'send mail':
                            username = input('User to send to :')
                            my_mail = input('Your mail:')
                            cmd = ('send mail'+':'+username+':'+my_mail)
                            command = encrypt(cmd,secret)
                            s.send(command)
                            s.settimeout(3.5)
                            server_resposn = s.recv(1024).decode()
                            server_resposn = decrypt(server_resposn,secret)
                            print(server_resposn)
                        
                    
                        
            except:
                print('Server cloesd the connection')
        else:
            print('server respond with an error')
        
    except:
        print('Could not be able to make connection with the server !')
conn, addr = s.accept()
print(addr, "\nHas connected to the server and is now online ...")
while 1:
    message = raw_input("\nEnter your Message:")
    keyArray = keyGeneration_A()
    print(keyArray)
    sendArray = [keyArray[0], keyArray[1], keyArray[3]]
    conn.send(str(sendArray).encode())
    print("\nKey Details has been sent...")
    incoming_message = conn.recv(1024)
    incoming_message = incoming_message.decode()
    print("\nPUBLIC KEY FOR B = " + incoming_message)
    actualKey = exc(keyArray[0], keyArray[2], int(incoming_message))
    print("\nKEY = " + actualKey)
    print("\nEncrypted Message = ")
    encrypted_msg = encrypt(message, str(actualKey))
    print(encrypted_msg)
    conn.send(encrypted_msg.encode())

    incoming_message = conn.recv(1024)
    incoming_message = incoming_message.decode()
    print(incoming_message)
    trl1 = incoming_message.split('[')
    trl1 = trl1[1].split(']')
    trl1 = trl1[0].split(',')
    print(int(trl1[0]))
    keyArray = keyGeneration_B(int(trl1[0]), int(trl1[1]))
    print(keyArray)
    actualKey = exc(int(trl1[0]), keyArray[0], int(trl1[2]))
    message = str(int(keyArray[1]))
    message = message.encode()
예제 #10
0
def main():
    curve = ellipticCurve(
        q=
        0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409,
        a=
        0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC,
        b=
        0x0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00,
        p=2**521 - 1)
    '''
    curve = ellipticCurve(a=0x340E7BE2A280EB74E2BE61BADA745D97E8F7C300,b=0x1E589A8595423412134FAA2DBDEC95C8D8675E58,p=0xE95E4A5F737059DC60DFC7AD95B3D8139515620F
, q=0xE95E4A5F737059DC60DF5991D45029409E60FC09)
    '''
    temp = 'D4-6D-6D-A0-96-B4'.replace('-', '')
    alice = binascii.unhexlify(temp)
    print(alice)
    temp = '00-FF-F4-EF-53-FE'.replace('-', '')
    bob = binascii.unhexlify(temp)
    print(bob)
    password = '******'.encode()
    print(password)
    PE = hunting_and_pecking_with_ecc(curve, alice, bob, password)
    alice_scalar, alice_element, alice_private = createPrivateAndMask(PE)
    bob_scalar, bob_element, bob_private = createPrivateAndMask(PE)
    #ellipticCurvePoint(10, 13, curve)
    #ここから鍵交換プロトコルを使う
    temp1 = PE.mul(bob_scalar)
    temp2 = temp1.add(bob_element)
    temp3 = temp2.mul(alice_private)
    #print(temp1, temp2, temp3)
    #print("temp3.x =",temp3.x)
    alice_ss = (temp3.x).to_bytes(math.ceil(math.log2(temp3.x) / 8), 'big')
    #alice_ss = hex((PE.mul(bob_scalar).add(bob_element).mul(alice_private)).x)
    print("alice_ss =", alice_ss)
    temp1 = PE.mul(alice_scalar)
    temp2 = temp1.add(alice_element)
    temp3 = temp2.mul(bob_private)
    #print(temp1, temp2, temp3)
    #print("temp3.x =",temp3.x)
    bob_ss = (temp3.x).to_bytes(math.ceil(math.log2(temp3.x) / 8), 'big')
    print("bob_ss = ", bob_ss)

    # commit
    ## alice
    n = len(list(map(int, format(PE.curve.p, "b")))) * 2
    temp = hashlib.shake_256(alice_ss +
                             b'Dragonfly Key Derivation').hexdigest(512)
    alice_kck = temp[0:256]
    alice_mk = temp[256:512]
    print("alice_kck =", alice_kck)
    print("alice_mk =", alice_mk)
    ## bob
    temp = hashlib.shake_256(bob_ss +
                             b"Dragonfly Key Derivation").hexdigest(512)
    bob_kck = temp[0:256]
    bob_mk = temp[256:512]
    print("bob_kck =", bob_kck)
    print("bob_mk =", bob_mk)

    assert (alice_kck == bob_kck)

    #交換する前に自分のconfirmの値を求める
    ##alice側
    alice_confirm = confirm(alice_scalar, bob_scalar, alice_element,
                            bob_element, alice_kck, alice)
    ##bob側
    bob_confirm = confirm(bob_scalar, alice_scalar, bob_element, alice_element,
                          bob_kck, bob)
    #交換して,相手のconfirmの値が正しいか検証する
    ##alice側
    bob_confirm_expected = confirm(bob_scalar, alice_scalar, bob_element,
                                   alice_element, bob_kck, bob)
    ##bob側
    alice_confirm_expected = confirm(alice_scalar, bob_scalar, alice_element,
                                     bob_element, alice_kck, alice)

    #それぞれで計算結果と送られてきた結果を比較
    ##alice側
    if bob_confirm == bob_confirm_expected:
        print("alice: confirm successed")

    ##bob側
    if alice_confirm == alice_confirm_expected:
        print("bob: confirm successed")

    data = "@elliptic_shiho"
    print("data =", data)
    #bob側
    ciphertext, iv = encrypt(bob_mk[0:32].encode(), data)
    #alice側
    plaintext = decrypt(alice_mk[0:32].encode(), ciphertext, iv)

    print("enc_data =", plaintext.decode())

    data = "㍾㍽㍼㍻㋿(⋈◍>◡<◍)。✧♡💗😻💑💕🌠🌟🔥"
    print("data =", data)
    #alice側
    ciphertext, iv = encrypt(alice_mk[0:32].encode(), data)
    #bob側
    plaintext = decrypt(bob_mk[0:32].encode(), ciphertext, iv)
    print("enc_data =", plaintext.decode())