예제 #1
0
    def encrypt(self, pt):
        self.buffer = bytearray()  #return할 buffer
        self.enciv = bytearray()  #암호화 시킨 iv를 한꺼번에 저장할 buffer
        self.pt = to_bytearray(pt)
        self.ptlength = len(pt)  #리턴시킬 암호문 길이
        '''
        block count 설정
        16배수면 그대로
        16배수가 아니면 padding을 통해 16배수로 만들어주고 count 설정
        '''
        cnt = int(len(pad(self.pt)) / self.block_size)
        if ((len(self.pt) % self.block_size) != 0):
            cnt = len(pad(self.pt)) / self.block_size
        '''
        iv 미리 계산
        '''

        tmp = self.iv  #입력 iv
        for i in range(cnt - 1):
            tmp = self.crypto.encrypt(tmp)
            self.enciv += tmp  #iv계산 저장
        '''
        암호화 진행
        '''
        for i in range(cnt):
            buf1 = self.enciv[(self.block_size * i):(self.block_size * i) +
                              self.block_size]  #block size에 맞게 미리 계산한 iv 자르기
            buf2 = self.pt[(self.block_size * i):(self.block_size * i) +
                           self.block_size]  #block size로 평문 자르기
            self.buffer += xorAr(buf1, buf2)  #xor 진행

        return self.buffer[:self.ptlength]  #평문 길이만큼 return
예제 #2
0
    def decrypt(self, ct):
        self.buffer = bytearray()  #return buffer
        self.enciv = bytearray()  #계산한 iv를 한꺼번에 저장할 buffer
        self.ctlength = len(ct)  #return할 cipher text의 길이 저장
        self.ct = ct
        '''
        16배수이면 그대로
        16배수가 아니면 패딩해서 16배수로 맞춘다음 count 설정
        '''
        cnt = int(len(pad(self.ct)) / self.block_size)
        if ((len(self.ct) % self.block_size) != 0):
            cnt = len(pad(self.ct)) / self.block_size
        '''
        iv 미리 계산
        '''
        tmp = self.iv
        for i in range(cnt - 1):
            tmp = self.crypto.encrypt(tmp)
            self.enciv += tmp

        for i in range(cnt):
            buf1 = self.enciv[
                (self.block_size * i):(self.block_size * i) +
                self.block_size]  #미리 계산한 enciv buffer를 block size에 맞게 자르기
            buf2 = self.ct[(self.block_size * i):(self.block_size * i) +
                           self.block_size]  #block size에 맞게 cipher text 자르기
            self.buffer += xorAr(buf1, buf2)  #xor 진행

        return self.buffer[:self.ctlength]
예제 #3
0
 def connect_to_cert(self):
     cert_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     cert_socket.connect(('127.0.0.1', 9000))
     print("[Bob] Now connected to Cert Authority")
     cert_socket.send(pad(b'Bob'))
     mess = cert_socket.recv(2000)
     mess = unpad(mess)
     if (mess == b'send'):
         cert_socket.send(pad(self.key_pair.publickey().export_key()))
     return
예제 #4
0
    def decrypt(self, ct):
        self.buffer = bytearray() #return buffer
        self.enciv = bytearray() #미리 계산할 iv를 저장하는 buffer
        self.ct = ct
        self.ctlength = len(ct) #return length

        '''
        만약 cipher block의 크기가 16의 배수가 아니면 padding해서 16배수로 맞춘다.
        '''
        if len(self.ct)%self.block_size != 0:
            self.ct = pad(ct)

        cnt = int(len(self.ct)/self.block_size)   #count setting    
        c0 = self.iv #초기 입력
        
        '''
        iv 미리 계산
        '''
        self.enciv += self.crypto.encrypt(c0) #cipher block 저장 (미리 iv 계산)
        for i in range(cnt-1):
            buf = self.ct[(self.block_size * i) : (self.block_size * i) + self.block_size] #cipher text 자르기
            self.enciv += self.crypto.encrypt(buf) #cipher block 추가

        '''
        복호화 진행
        '''
        for i in range(cnt):
            buf1 = self.enciv[(self.block_size * i) : (self.block_size*i) + self.block_size] #미리 계산한 iv를 block size에 맞게 자르기
            buf2 = self.ct[(self.block_size * i) : (self.block_size*i) + self.block_size] #block size에 맞게 cipher text 자르기
            self.buffer += xorAr(buf1,buf2)   #xor 진행
        return self.buffer[:self.ctlength]
예제 #5
0
    def connect_to_cert(self):
        cert_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        cert_socket.connect(('127.0.0.1', 9000))
        print("[Alice] Now connected to Cert Authority")
        cert_socket.send(pad(b'Alice'))
        b = cert_socket.recv(2000)
        b = unpad(b)
        if(b == b'send'):
            cert_socket.send(pad(self.key_pair.publickey().export_key()))
            b=unpad(cert_socket.recv(2000))
        if(b == b'nonce,ts'):
            nonce = random.randint(1,20000)
            timestamp = datetime.now()
            self.timestamp = timestamp
            cert_socket.send(pad(bytes(str(nonce)+","+format(timestamp),"utf-8")))
        try:
            cipher_rsa = PKCS1_OAEP.new(self.key_pair)
        
            ## my nonce
            nonce_c        = cert_socket.recv(256)
            ## my timestamp
            timestamp_c    = cert_socket.recv(256)
            ## c pub key
            self.c_pub_key = RSA.import_key(unpad(cert_socket.recv(2000)))
            ## checksum
            checksum       = cert_socket.recv(256)
            
            # check integrity
            nonce_d        = cipher_rsa.decrypt(nonce_c)
            timestamp_d    = parser.parse(cipher_rsa.decrypt(timestamp_c).decode())
            hash_object    = SHA256.new(data=nonce_c)
            hash_object.update(data=timestamp_c)
            
            assert(int(nonce_d)==nonce)
            assert(hash_object.digest() == checksum)
            assert(timestamp_d.strftime("%H:%M:%S")==timestamp.strftime("%H:%M:%S"))

            ## Send Symmetric-Key to C and wait for Bob
            cipher_rsa_c = PKCS1_OAEP.new(self.c_pub_key)
            cert_socket.send(cipher_rsa_c.encrypt(self.ab_key))
            cert_socket.send(cipher_rsa_c.encrypt(str(self.PORT).encode()))
        except:
            print("[Alice] See Ya")
            return
        print("[Alice] wait for Bob")
        return
예제 #6
0
 def connect_to_alice(self, port):
     alice_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     alice_socket.connect(('127.0.0.1', port))
     alice_socket.send(pad(b'Bob'))
     cipher = AES.new(self.ab_key, AES.MODE_ECB)
     timestamp_to_a = cipher.encrypt(
         Padding.pad(
             self.a_timestamp.strftime("%H:%M:%S").encode(),
             AES.block_size))
     alice_socket.send(timestamp_to_a)
     time.sleep(0.1)
     print("[Bob] Now connected to Alice")
예제 #7
0
    def encrypt(self, pt):
        self.buffer = bytearray()  #리턴할 buffer

        self.pt = pad(pt)  #padding
        self.pt = to_bytearray(self.pt)  #to bytearray
        cnt = int(len(self.pt) / self.block_size)  #count
        '''
        암호화 진행
        '''
        for i in range(cnt):
            buf = self.pt[(self.block_size * i):(self.block_size * i) +
                          self.block_size]  #block 자르기
            enc = self.crypto.encrypt(buf)
            self.buffer += enc

        return self.buffer
예제 #8
0
    def decrypt(self, ct):
        self.buffer = bytearray()  #return buffer
        self.ct = ct
        self.ctlength = len(ct)  #return length
        '''
        16의 배수에 맞게 cnt 설정
        '''
        cnt = int(len(self.ct) / self.bloc_size)
        if ((len(self.ct) / self.bloc_size) != 0):
            cnt = len(pad(self.ct))

        for i in range(cnt):
            self.buffer += xorAr(self.crypto.encrypt(
                self.ctr), self.ct[(self.bloc_size * i):(self.bloc_size * i) +
                                   self.bloc_size])  #암호화 진행
            self.cal_ctr()  #ctr update

        return self.buffer[:self.ctlength]
예제 #9
0
    def encrypt(self, pt):
        self.buffer = bytearray() #return buffer
        self.pt = to_bytearray(pt) #plain text convert to bytearray
        self.ptlength = len(pt) #return할 cipher ptext 길이
        
        
        '''
        평문의 길이가 16의 배수이면 그대로 cnt설정
        16의 배수가 아니면 padding을 해서 16의 배수로 만든 다음 cnt 설정
        '''
        cnt = int(len(self.pt)/self.block_size)
        if((len(self.pt)/self.block_size) != 0):
            cnt = len(pad(self.pt))
        
        c0 = self.iv #cipher block
        for i in range(cnt-1):
            buf = self.pt[(self.block_size * i) : (self.block_size*i) + self.block_size] #block size로 plain text 자르기
            c0 = self.crypto.encrypt(c0) #암호화
            c0 = xorAr(buf, c0) #xor 진행 and cipher block update
            self.buffer += c0 #adding block
            

        
        return self.buffer[:self.ptlength]
    def forward(self, utterances, utterances_mask, roles, conversation_mask,
                conversation_length):
        '''

        :param input:
            - utterances = [batch_size * utt_num] * max_seq_len
            - utterances_mask = [batchsize * utt_num] * max_seq_len
            - roles = batch_size * max_turn_len
            - conversation_mask = batch_size * max_turn_len
            - conversation_length = batch_size

        :return: output: batchsize * max_turn_len * output_size
        '''
        '''
        bert layer
        since [batch_size * utt_num] may be too large, divide into bert_batch_size * max_seq_len pieces to go through the bert
        '''
        num_sentences = utterances.size(0)

        input_utterances = [
            utterances[i:i + self.bert_batch_size, :]
            for i in range(0, num_sentences, self.bert_batch_size)
        ]
        input_utterances_masks = [
            utterances_mask[i:i + self.bert_batch_size, :]
            for i in range(0, num_sentences, self.bert_batch_size)
        ]

        bert_encoded_embeds = [
        ]  # [batch_size utt_num] * max_seq_len * hidden_size

        for input_utterances_piece, input_utterances_masks_piece in zip(
                input_utterances, input_utterances_masks):
            _, _, bert_encoded_piece = self.bert_layer(
                input_utterances_piece, input_utterances_masks_piece)
            # extract output tensor from the second-to-last layer and average pooling
            # use the [CLS] for sentence embedding
            # bert_batch_size * hidden_size
            bert_encoded_piece = torch.stack(tuple(
                bert_encoded_piece[i]
                for i in range(2, len(bert_encoded_piece), 1)),
                                             dim=0)

            bert_encoded_piece = torch.mean(bert_encoded_piece[:, :, 0, :],
                                            dim=0)

            bert_encoded_embeds += bert_encoded_piece.tolist()

        # recover to batch_size * max_turn_len * hidden_size
        max_turn_len = conversation_mask.size(1)

        start = torch.cumsum(
            torch.cat((conversation_length.new(1).zero_(),
                       conversation_length[:-1])), 0)

        bert_encoded_embeds = torch.stack([
            pad(
                torch.tensor(
                    bert_encoded_embeds, dtype=torch.float32).cuda().narrow(
                        0, s, l), max_turn_len)
            for s, l in zip(start.data.tolist(),
                            conversation_length.data.tolist())
        ], 0).cuda()  # batchsize * max_turn_len * hidden_size
        '''TCN
        Input ought to have dimension (N, C_in, L_in), where L_in is the seq_len; here the input is (N, L, C)
        Ouput batch_size * max_turn_len * output_size
        '''
        # emb = self.drop(bert_encoded_embeds)
        emb = bert_encoded_embeds

        y = self.tcn(emb.transpose(1, 2)).transpose(1, 2)
        y = self.linear_layer(y)

        # add
        y = self.sig(y)

        return y
예제 #11
0
    def callback(self, conn, addr):
        print("[Auth]" + str(addr) + " is now connected to Cert Authority")
        data = conn.recv(2000)
        data = unpad(data)
        decoded = data.decode("utf-8")
        ## If ALICE
        if (decoded == 'Alice'):

            ## Handshake
            #self.alice_port   = int(decoded.split("on")[1])
            self.alice_socket = conn
            self.alice_socket.send(pad(b'send'))
            self.alice_pub_key = RSA.import_key(
                unpad(self.alice_socket.recv(2000)))
            print("[Auth] got alice key")

            ## Recive Nonce and Timestamp
            time_now = datetime.now()
            self.alice_socket.send(pad(b'nonce,ts'))

            mess = self.alice_socket.recv(2000)

            try:
                nonce = mess.decode("utf-8").split(",")[0]
                timestamp = mess.decode("utf-8").split(",")[1]
                date_time_obj = parser.parse(timestamp)
                hms = date_time_obj.strftime("%H:%M:%S")
            except:
                print("[Auth] Timeout Expired")
                return

            ## Send back Encrypted Nonce and Timestamp and my pub_key
            cipher_rsa_c = PKCS1_OAEP.new(self.key_pair)
            cipher_rsa_ac = PKCS1_OAEP.new(self.alice_pub_key)
            cipher_rsa_bc = PKCS1_OAEP.new(self.bob_pub_key)
            if ((date_time_obj - time_now).seconds < 10):

                nonce_c = cipher_rsa_ac.encrypt(bytes(nonce, "utf-8"))
                a_timestamp = cipher_rsa_ac.encrypt(format(hms).encode())
                c_pub_key = self.key_pair.publickey().export_key()

                hash_object = SHA256.new(data=nonce_c)
                hash_object.update(data=a_timestamp)

                self.alice_socket.send(nonce_c)
                self.alice_socket.send(a_timestamp)
                self.alice_socket.send(pad(c_pub_key))
                self.alice_socket.send(hash_object.digest())

                ## Reciva AB key from A
                ab_key_enc = self.alice_socket.recv(256)
                ab_key = cipher_rsa_c.decrypt(ab_key_enc)
                self.alice_port = int(
                    cipher_rsa_c.decrypt(self.alice_socket.recv(256)).decode())
                print("[Auth] recvd key and port from Alice")

                ## Send AB Key and TS To bob
                self.bob_socket = socket.socket(socket.AF_INET,
                                                socket.SOCK_STREAM)
                self.bob_socket.connect(('127.0.0.1', 8000))
                self.bob_socket.send(pad(b'Cert'))
                self.bob_socket.send(cipher_rsa_bc.encrypt(ab_key))
                self.bob_socket.send(cipher_rsa_bc.encrypt(hms.encode()))
                self.bob_socket.send(
                    cipher_rsa_bc.encrypt(str(self.alice_port).encode()))

            else:
                print("[Auth] Timeout Expired")
                return
            return
        elif (decoded == 'Bob'):
            self.bob_socket = conn
            self.bob_socket.send(pad(b'send'))
            self.bob_pub_key = RSA.import_key(unpad(
                self.bob_socket.recv(2000)))
            print("[Auth] got bob key")
            return
        else:
            print("[Auth] Not identified! closing connection")
            return
        return