[목차]

 

 

1. 소켓 프로그래밍 실습2

   * 프로그램 시나리오

   * 3DES 암복호화 프로그램

   * 메시지를 암호화해 전송하는 클라이언트

   * 메시지를 받아 복호화 하는 서버

 

 

 

 


 

 

 

 

[소켓 프로그램 실습2]

 

 

 

 

1. 프로그램 시나리오

 

 

ㄱ) 준비사항

1) file.in(Plaintext.txt 파일 사용)

Robin Monroe (Anne Heche) is a New York City journalist who works for Dazzle, a fashion magazine. She is invited by her boyfriend Frank (David Schwimmer) to spend a week holidaying with him on the island paradise of Makatea, in the South Pacific. The final leg of their journey to Makatea is in a dilapidated de Havilland Canada DHC-2 Beaver, piloted by middle-aged American Quinn Harris (Harrison Ford). They are accompanied by Quinn's girlfriend and co-pilot Angelica (Jacqueline Obradors). On their first night on the island, Frank proposes to Robin, who happily accepts. At a bar, a drunken Quinn makes a move on Robin, which she rejects as Frank appears.

 

 

2) DES3FromMsg2.py 파일

* msg -> E(msg) -> encmsg

* encmsg -> D(encmsg) -> decmsg

 

 

3) ServerDES2.py/clientDES2.py 제작

작성할때는 클라이언트를 먼저 만들어야 한다

데이터를 보내봐야 하기 때문.

 

* Clientside

file(p) -> msg -> E(msg) -> encmsg --> 전송

 

* Serverside

전송된 메시지 (encmsg) -> D(encmsg)

 

 

 

 

2. 3DES 암복호화 프로그램 제작

DES3FromMsg2.py

from Crypto.Cipher import DES3 as DES
from Crypto.Hash import SHA256 as SHA


class MyDES():    #상속받는게 없으니 괄호 빼도됨

    def __init__(self, key, iv):
        myhash = SHA.new()

        myhash.update(key.encode())
        tkey = myhash.digest()
        self.key = tkey[:24] # self = 전역변수로 사용됨. key '' 이렇게 클래스 바로 밑에 정의해 둬도 됨

        myhash.update(iv.encode())
        tiv = myhash.digest()
        self.iv = tiv[:8]

        #self.en_msg = msg.encode() 아래 msg를 따로 만들자

    def enc(self, msg):
        # input : str(plaintext)
        # output : b'str(encmsg)
        #print("==> ", msg)
        msg = self.make8string(msg)
        #print("==> ", msg) ; input()
        des3 = DES.new(self.key, DES.MODE_CBC, self.iv)
        encmsg = des3.encrypt(msg.encode()) # 암호화 하는 자리


        return encmsg


    def convertFromFileToEncmsg(self, filename):
        # input : file(filename)
        # output : b'str(encmsg)
        # function :
        fd = open(filename)
        encmsg = self.enc(fd.read())
        fd.close()

        return encmsg


    def dec(self, msg):
        des3 = DES.new(self.key, DES.MODE_CBC, self.iv)
        decmsg = des3.decrypt(msg)

        return decmsg

    def convertFromMsgToFile(self, msg):
        decmsg = self.dec(msg)
        decmsg = decmsg.decode()

        filename = 'Plain2.txt.enc'
        fd = open(filename, 'w+')
        fd.write(decmsg)
        fd.close()

        return filename


    def make8string(self, msg):
        msglen = len(msg)
        fillter = ''
        if msglen % 8 != 0:
            fillter = 'O' * (8 - msglen % 8)
        msg += fillter

        return msg

def main():
    # mymsg = 'We are no longer the knights who say ni!'
    mymsg = 'abcde'
    mykey = 'samsjang'
    myiv = '1234'
    myfile = 'Plaintext.txt'

    mycipher = MyDES(mykey, myiv)
    encrypted = mycipher.convertFromFileToEncmsg(myfile)
    print('Plaintext  :', open(myfile).read())
    print('Encrypted  :', encrypted)
    # input()

    decryptedfile = mycipher.convertFromMsgToFile(encrypted)
    print('Decrypted  :', open(decryptedfile).read())


if __name__ == '__main__':
    main()

 

 

 

 

3. 메시지를 암호화해 전송하는 클라이언트

ClientDES2.py

# Ready:
#   * file.in(pliantext.txt)
#   * DES3FromMSG2.py
# File(file.in) -> msg -> E(msg) -> encmsg -> socket(send_encmsg) -> Server Side

import sys
import os
import socket
from Crypto.Hash import SHA256 as SHA

try:
    import DES3FromMsg2
except Exception as e:
    sys.exit("Error:", e)


def main():
    keytext = 'samsjang'
    ivtext = '1234'
    myfile = 'file.in'

    mycipher = DES3FromMsg2.MyDES(keytext, ivtext)
    encmsg = mycipher.convertFromFileToEncmsg(myfile)
    print("Plaintext File Content" + "(file.in):", open(myfile).read() )
    print("Ciphertext Msg Content:", encmsg)

    host = '127.0.0.1'
    port = 4444
    send_encdata(host, port, encmsg)


def send_encdata(host, port, encmsg):
    try:
        s = socket.socket()
        s.connect((host, port))
        s.sendall(encmsg)
    except Exception as e:
        sys.exit('Error:', e)
    finally:
        s.close()


if __name__ == "__main__":
    main()

 

 

 

 

4. 메시지를 받아 복호화 하는 서버

ServerDES2.py

import os
import sys
import socket


try:
    import DES3FromMsg2
except Exception as e:
    sys.exit('Error:', e)


def main():
    # 1) received msg(encrypted message)
    # 2) save encrypted message in file

    host = '127.0.0.1'
    port = 4444
    encmsg = recv_encdata(host, port)
    print("Recieved Msg", encmsg)

    ivtext = '1234'
    keytext = 'samsjang'
    mycipher = DES3FromMsg2.MyDES(keytext, ivtext)
    filename = mycipher.convertFromMsgToFile(encmsg)
    print("File Name:", filename)
    print("Decrypted File Content:", open(filename).read())

def recv_encdata(host, port):
    try:
        s = socket.socket()
        s.bind((host, port))
        s.listen()
        client, addr = s.accept()

    except Exception as e:
        sys.exit('Error: ', e)
    else:
        content = b''
        print("Connected by", addr)
        while True:
            data = client.recv(2048)
            # print("Recieved Msg", data)
            if not data:
                client.close()
                break
            content += data
        # print("Recieved Msg2 :", content)
        return content


if __name__ == '__main__':
    main()

 

 

 


 

 

 

 

 

728x90

+ Recent posts