コード例 #1
0
ファイル: IoTserver.py プロジェクト: pjoseph3/SecureIoT
def validate_ticket(data):
    data_dict = json.loads(data)
    ticket = DES.decrypt(IOTKEY[:8], base64.b64decode(data_dict["ticket"]))
    ticket_dict = json.loads(ticket)
    try:
        sessionkey = base64.b64decode(ticket_dict["sessionkey"])
        authenticator = json.loads(
            DES.decrypt(sessionkey[16:24],
                        base64.b64decode(data_dict["authenticator"])).decode())
    except:
        return None
    timestamp = datetime.strptime(authenticator["timestamp"],
                                  '%Y-%m-%d %H:%M:%S.%f')
    lifetime = datetime.strptime(ticket_dict["lifetime"],
                                 '%Y-%m-%d %H:%M:%S.%f')
    if authenticator["logout"] == "True":
        authenticator_set.clear()
        print("authenticator_list:\n", authenticator_set)
        return "Successfully logged out from IoT.", "logout"
    if datetime.now() > lifetime:
        authenticator_set.clear()
        return "expired"
    if authenticator["username"] != ticket_dict["username"]:
        return None
    if data_dict["server"] != ticket_dict["server"]:
        return None
    if (authenticator["username"], timestamp) in authenticator_set:
        return None
    authenticator_set.add((authenticator["username"], timestamp))
    print("authenticator_list:\n", authenticator_set)
    return data_dict["command"]
コード例 #2
0
def TGS_server(info: dict):
    tgt_encr = info['tgt']
    auth_encr = info['auth']
    service_id = info['id']

    tgt = DES.decrypt(tgt_encr, database.K_as_tgs)
    tgt = eval(tgt)
    k_c_tgs = tgt['key']

    auth = DES.decrypt(auth_encr, tgt['key'])
    auth = eval(auth)

    if auth['c'] != tgt['c']:
        raise ValueError('client id not equal')

    if auth['time'] - tgt['time'] > tgt['period']:
        raise ValueError('ticket is not valid')

    k_tgs_ss = database.keys[(service_id, database.tgs_id)]
    k_c_ss = database.keys[tuple(sorted((service_id, auth['c'])))]

    tgs = {
        'c': auth['c'],
        'ss': service_id,
        'time': datetime.now().timestamp(),
        'period': 1000,
        'key': k_c_ss
    }

    res = {
        'tgs': DES.encrypt(str(tgs), k_tgs_ss),
        'key': k_c_ss
    }

    return DES.encrypt(str(res), k_c_tgs)
コード例 #3
0
def main():
    TCP_IP = '127.0.0.1'
    SERV_PORT = 5005
    BOB_PORT = 5004
    ALICE_PORT = 5003
    BUFFER_SIZE = 4096

    #connect to KDC to establish aliceKey
    servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    servSock.connect((TCP_IP, SERV_PORT))
    #clients are aware of each others' usernames
    alice = "Alice"
    bob = "Bob"
    servSock.send(alice.encode("utf-8"))
    aliceKey = diffieHellman(servSock, False)
    aliceNonce = generate_nonce()
    namePrint(alice, "aliceKey established with server as " + str(aliceKey))

    #connect to Bob to start exchanging information
    bobSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    bobSock.connect((TCP_IP, BOB_PORT))

    #1. Alice sends a request to Bob
    namePrint(alice, "step 1: request to Bob")
    msg = [alice]
    sendMessage(bobSock, msg)

    #3. Alice sends a message to the server identifying herself and Bob, telling the server she wants to communicate with Bob.
    namePrint(alice, "step 3: request to Server")
    encryptedMsg = receiveMessage(bobSock)
    msg = [alice, bob, aliceNonce, encryptedMsg]
    sendMessage(servSock, msg)

    #5. Alice forwards the key to Bob who can decrypt it with the key he shares with the server, thus authenticating the data.
    namePrint(alice, "step 5: pass Server response to Bob")
    encryptedNewMsg = receiveMessage(servSock)
    decryptedServerMsg = DES.frombits(DES.decrypt(encryptedNewMsg, aliceKey))
    serverMsg = decoder.decode(decryptedServerMsg)
    aliceKab = serverMsg[2]
    toBob = serverMsg[3]
    sendMessage(bobSock, toBob)

    #7. Alice performs a simple operation on the nonce, re-encrypts it and sends it back verifying that she is still alive and that she holds the key.
    namePrint(alice, "step 7: send nonce operation result to Bob")
    encryptedNewMsg = receiveMessage(bobSock)
    decryptedBobMsg = DES.frombits(DES.decrypt(encryptedNewMsg, aliceKab))
    decryptedBob = decoder.decode(decryptedBobMsg)
    newMsg = [nonceSubtract(decryptedBob[0])]
    encryptedNewMsg = DES.encrypt(DES.tobits(encoder.encode(newMsg)), aliceKab)
    sendMessage(bobSock, encryptedNewMsg)

    #time too chat!
    namePrint(alice, "Success! Time to chat!")
    threading.Thread(target=chatDataHandler,
                     args=(bobSock, bob, aliceKab)).start()
    while (True):
        sendMessage(
            bobSock,
            DES.encrypt(DES.tobits(encoder.encode(input(""))), aliceKab))
コード例 #4
0
def ss_server(tgs_ans):
    time = datetime.datetime.now().timestamp()
    info = {
        'tgs': tgs_ans['tgs'],
        'auth': DES.encrypt(str({
            'c': __client,
            'time': time
        }), tgs_ans['key'])
    }

    print('\n\tRequest to SS_server:')
    print(info)

    res_encr = SS_server(info)

    print('\n\tSS_server encrypted response:')
    print(res_encr)
    res = eval(DES.decrypt(res_encr, tgs_ans['key']))

    print('\n\tSS_server decrypted response:')
    print(res)

    if abs(res - time - 1) > 1e-6:
        raise ValueError("Not connected")

    print('\n\nOK. Connected')
コード例 #5
0
def tgs_server(auth):
    info = {
        'tgt':
        auth['tgt'],
        'auth':
        DES.encrypt(
            str({
                'c': __client,
                'time': datetime.datetime.now().timestamp()
            }), auth['key']),
        'id':
        __target
    }

    print('\n\tRequest to TGS_server:')
    print(info)

    res_encr = TGS_server(info)

    print('\n\tTGS_server encrypted response:')
    print(res_encr)

    res = DES.decrypt(res_encr, auth['key'])

    print('\n\tTGS_server decrypted response:')
    print(res)

    return eval(res)
コード例 #6
0
ファイル: demo.py プロジェクト: 12345bt/DES1
def main():
    des = DES()
    Des_IV = "Passw0rd"
    encode = des.encrypt("Passw0rd", Des_IV, str("Hello World!"))
    encode2 = des.decrypt("Passw0rd", Des_IV,
                          str("53c8927a4dd1e9b6f44c9d53af92c794"))
    print(encode)

    print(encode2)
コード例 #7
0
def SS_server(info):
    auth_encr = info['auth']
    tgs_encr = info['tgs']

    key_tgs_ss = database.keys[(__server, __tgs)]
    tgs = DES.decrypt(tgs_encr, key_tgs_ss)
    tgs = eval(tgs)
    key_c_ss = tgs['key']
    auth = DES.decrypt(auth_encr, key_c_ss)
    auth = eval(auth)

    if auth['c'] != tgs['c']:
        raise ValueError('Clients not equal')
    if auth['time'] - tgs['time'] > tgs['period']:
        raise ValueError('Period is not valid')

    response = auth['time'] + 1

    return DES.encrypt(str(response), key_c_ss)
コード例 #8
0
def main():
    TCP_IP = '127.0.0.1'
    SERV_PORT = 5005
    BUFFER_SIZE = 4096

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, SERV_PORT))
    s.listen(1)
    names = []
    keys = []
    for i in range(2):
        print(
            "Server: Awaiting {0} connection to establish diffie-hellman key.."
            .format("first" if i == 0 else "second"))
        conn, addr = s.accept()
        names.append(conn.recv(BUFFER_SIZE).decode("utf-8"))
        print(
            "Server: Connected to {0}. Running diffieHellman for initial key.".
            format(names[i]))
        keys.append(diffieHellman(conn, True))
        print("Server: server key for {0}: {1}".format(names[i], keys[i]))
        if (i == 0):
            #close Bob's connection, but keep Alice open for a bit longer
            conn.close()
    bobKey = keys[0]
    aliceKey = keys[1]

    #generate random session key on the server for alice and bob to communicate
    Kab = [random.randint(0, 1) for _ in range(10)]

    #4. The server generates K_AB and sends back to Alice a copy encrypted under K_BS for Alice to forward to Bob and also a copy for Alice.
    #Since Alice may be requesting keys for several different people, the nonce assures Alice that the message is fresh and that
    #the server is replying to that particular message and the inclusion of Bob's name tells Alice who she is to share this key with.
    #Note the inclusion of the nonce.
    print(
        "Server: step 4: generate K_AB and send double encrypted message to Alice"
    )
    msg = receiveMessage(conn)
    decryptedBobMsg = DES.frombits(DES.decrypt(msg[3], bobKey))
    decryptedBob = decoder.decode(decryptedBobMsg)
    decryptedBob.append(Kab)

    reEncryptedBob = DES.encrypt(DES.tobits(encoder.encode(decryptedBob)),
                                 bobKey)
    newMsg = [msg[1], msg[2], Kab, reEncryptedBob]
    encryptedNewMsg = DES.encrypt(DES.tobits(encoder.encode(newMsg)), aliceKey)
    sendMessage(conn, encryptedNewMsg)
    conn.close()

    input("Server: My part is done. Press enter to exit...")
コード例 #9
0
def authorization():
    authorization_decr = AS_server(__client)
    if not authorization_decr:
        raise ValueError('No such user in database')

    print('\tAS_server encrypted response:')
    print(authorization_decr)

    authorization = DES.decrypt(authorization_decr, __client_key)

    print('\n\tAS_server decrypted response:')
    print(authorization)

    return eval(authorization)
コード例 #10
0
ファイル: client.py プロジェクト: Dimarnachos/IoTarchitecture
def decrypt_message(data, pw):
    if data == "Nice try buddie ;-)":
        return None

    data_dict = json.loads(data)
    salt = base64.b64decode(data_dict["salt"])
    key = hash.hashed_pw(pw, salt)
    packet = DES.decrypt(key[48:56], base64.b64decode(data_dict["payload"]))
    try:
        ticket = json.loads(packet.decode())
    except:
        ticket = None

    if not ticket:
        return None
    return ticket
コード例 #11
0
def Main():
    host = "127.0.0.1"
    port = 4500

    # start out with the key, CHANGE KEY HERE
    key10bit = '1010101010'
    k1, k2 = DES.generateKeys(key10bit)

    # bind the socket to host and port
    mySocket = socket.socket()
    mySocket.bind((host, port))

    # pass 1 to the listen socket so it listens forever
    mySocket.listen(1)
    conn, addr = mySocket.accept()
    print("Connection from: " + str(addr))

    # run untill connection is closed
    while True:
        # must decode connection bc normal string won’t pass through socket
        # str does not implement buffer interface
        data = conn.recv(1024).decode()
        if not data:
            break
        # if this is the first time, don't call any decodeing/ encrypting functions
        if data.lower() == 'a':
            conn.send(data.encode())
            continue

        print("from connected  user: "******"sending: " + str(data))
        # calls decrypt function on recieved encrypted message
        plain_txt = DES.decrypt(data, k1, k2)
        # send back decrypted message (plain text)
        conn.send(plain_txt.encode())
    # close the connection
    conn.close()
コード例 #12
0
ファイル: main.py プロジェクト: Jianfei2333/info_security
def decryptor():
    everything = read_str('密文,补充位数,密钥,用空格间隔')
    cipher = everything.split(' ')[0]
    addition = everything.split(' ')[1]
    key = everything.split(' ')[2]
    # 密文 cipher
    # 补充位数 addition
    # 密钥 key
    k = _2bin(key)
    # 裁剪:
    decrypt_package = cut(_2bin(cipher), 64)
    plain = ""
    if (decrypt_package['addition_count'] != 0):
        print(
            "Error: Bits check failed, maybe the cipher you've input was wrong?"
        )
        return
    else:
        for d in decrypt_package["data"]:
            node = DES.decrypt(d, k, silence=True)
            plain += node
    plain = plain[:-int(addition)]
    print(plain)
    print(decode(plain))
コード例 #13
0
from DES import *

myDES = DES();

plaintext = '0123456789ABCDEF';
key       = '133457799BBCDFF1';

ciphertext = myDES.encrypt(plaintext, key)
decrypted  = myDES.decrypt(ciphertext,key)

print('##########')
print('key        = ' + key       )
print('ciphertext = ' + ciphertext)
print('plaintext  = ' + plaintext )
print('decrypted  = ' + decrypted )

コード例 #14
0
ファイル: main.py プロジェクト: rystills/CSCI6230-HW2
def chatDataHandler(sock, oName, kab):
    while True:
        namePrint(oName, DES.frombits(DES.decrypt(receiveMessage(sock), kab)))
コード例 #15
0
ファイル: Bob.py プロジェクト: rystills/CSCI6230-HW2
def main():
    TCP_IP = '127.0.0.1'
    SERV_PORT = 5005
    BOB_PORT = 5004
    BUFFER_SIZE = 4096
    
    #connect to KDC to establish bobKey
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, SERV_PORT))
    #clients are aware of each others' usernames
    alice = "Alice"
    bob = "Bob"
    s.send(bob.encode("utf-8"))
    bobKey = diffieHellman(s, False)
    s.close()
    bobNonce = generate_nonce()
    bobNoncePrime = generate_nonce()
    namePrint(bob,"bobKey established with server as " + str(bobKey))
    
    #prepare for a connection from Alice
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, BOB_PORT))
    s.listen(1)
    conn, addr = s.accept()
    
    #2. Bob responds with a nonce encrypted under his key with the Server
    namePrint(bob,"step 2: send Alice noncePrime")
    msg = receiveMessage(conn)
    msg.append(bobNoncePrime)
    encryptedMsg = DES.encrypt(DES.tobits(encoder.encode(msg)),bobKey)
    sendMessage(conn, encryptedMsg)
    
    #6. Bob sends Alice a nonce encrypted under K_AB to show that he has the key.
    namePrint(bob,"step 6: send Alice nonce encrypted under K_AB")
    toBob = receiveMessage(conn)
    decryptedAliceMsg = DES.frombits(DES.decrypt(toBob,bobKey))
    decryptedAlice = decoder.decode(decryptedAliceMsg)
    #verify that bobNoncePrime made it back 
    if (decryptedAlice[1] != bobNoncePrime):
        namePrint(bob,"Error: Bob Nonce Prime has been corrupted! Aborting in case of attack.")
        sys.exit()
    bobKab = decryptedAlice[2]
    newMsg = [bobNonce]
    encryptedNewMsg = DES.encrypt(DES.tobits(encoder.encode(newMsg)),bobKab)
    sendMessage(conn, encryptedNewMsg)
    
    #8. Bob see's that Alice's computation was correct. Hurray, we're ready to chat!
    namePrint(bob,"step 8: verify Alice nonce operation result")
    encryptedNewMsg = receiveMessage(conn)
    decryptedAliceMsg = DES.frombits(DES.decrypt(encryptedNewMsg,bobKab))
    decryptedAlice = decoder.decode(decryptedAliceMsg)
    if (decryptedAlice[0] == nonceSubtract(bobNonce)):
        namePrint(bob,"Success! Time to chat!")
    else:
        namePrint(bob,"Error: Did not receive Bob Nonce - 1 from Alice")
        sys.exit()
    
    #time to chat!
    threading.Thread(target=chatDataHandler, args = (conn, alice, bobKab)).start()
    while (True):
        sendMessage(conn,DES.encrypt(DES.tobits(encoder.encode(input(""))),bobKab))
コード例 #16
0
ファイル: testing.py プロジェクト: pvinicki/CryptoSys
import DES as des
import binascii
import os
import sys

text = des.encrypt('0123456789ABCDEF', '133457799BBCDFF1', False)
print(text)

result = des.decrypt(text, '133457799BBCDFF1')
print(result)

#print(bin(int('123', 16))[2:].zfill(12))
#decrypted = des.decrypt(text, 'EAB234CA5B2D3572')
#print(decrypted)

#bits = '1011'
#temp = '1111'
#temp = int(temp, 2)
#bits = int(bits, 2)

#fillBits = int(bin(bits >> 3)[2:].zfill(4),2)
#leftShift = int(bin(temp & bits << 1)[2:].zfill(4),2)

#result = bin((temp & bits << 1) | int(bin((bits >> (3)))[2:].zfill(4), 2))[2:]
#result = bin((temp & (bits << 1)) | int(bin((bits >> (4 - 1)))[2:].zfill(4), 2))[2:]

#print(leftShift)
#print(fillBits)

#print(bin(leftShift | fillBits)[2:].zfill(4))