RSA 암호화 한 공개키를 클라이언트에게 보내고싶습니다.

익명 사용자의 이미지

MFC에서 Winsock을 이용한 socket 통신을 해보고 있습니다.
서버와 클라이언트 둘다 잘 되는 상황이고 서로 주고 받는 텍스트를 암호화 해서 보내고 받는걸 구현중입니다.

RSA 구현 알고리즘등을 검색해서 코드는 짜놨지만 서버가 접속한 클라이언트에게 공개키를 줄때 문제가 생기네요

int 값인 공개키를 send하려고 sprintf로 char형변환을 시켜서 보내려고 했습니다. 처음에 보낼 때 공개키가 가기는 가는데 이상한 값도 따라들어가네요 어떤값이 출력되는지 이미지로 올리겠습니다.

어떻게 수정해야할지 모르곘습니다...

RSA.cpp 입니다.

#include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include "encryption.h"
 
 
Encryption::Encryption() {};
Encryption::~Encryption() {};
 
// p, q
void Encryption::Selectpq() 
{
    int random;
    int i, j;
    srand((unsigned)time(NULL));
    random = (rand() % 1000); 
    int ck, ck2 = 0;
    for (i = random; 1; i++)
    {
        for (j = 2; j < i / 2 + 1; j++)
        {
            if (i%j == 0)
            {
                ck = 1;
                break;
            }
            ck = 0;
        }
        if (ck == 0 && ck2 == 1)
        {
            second = i;
            break;
        }
        if (ck == 0 && ck2 == 0)
        {
            first = i;
            ck2 = 1;
        }
 
    }
}
//pi e (1 < e < pi)
void Encryption::SelectEulerETC()
{
    int i, j, tmp = 1;
    pub_Key_First = first * second;
    eulerPi = (first - 1) * (second - 1);
    for (i = 2; i < eulerPi; i++)
    {
        for (j = 1; j <= i; j++)
        {
            if (i%j == 0 && eulerPi%j == 0)
                tmp = j;
        }
        if (tmp == 1)
        {
            pub_Key_Second = i;
            break;
        }
        tmp = 1;
    }
}
//d
void Encryption::SelectPriKey()
{
    int i;
    for (i = 2; i < eulerPi; i++)
    {
        if ((pub_Key_Second * i) % eulerPi == 1)
            pri_Key = i;
    }
}
 
c = m^e mod n
void Encryption::Enc(char buffer[], int bufsize)
{
    for (int k = 0; k == bufsize; k++)
    {
        encrypt[k] = buffer[k];
    }
    for (int i = 0; i < bufsize; i++)
    {
        for (int j = 0; j < pub_Key_Second; j++) // c = m^e mod n
        {
            sum *= (int)encrypt[i]; 
            sum %= pub_Key_First;
            encryptDone[j] = sum;
        }
 
    }
}
// m = c^d mod n
void Encryption::Decryption(char buffer[], int bufsize)
{
    while (decrypt != bufsize)
    {
        for (int j = 0; j < pri_Key; j++)
        {
            word = buffer[j];
            sum *= word; // m = c^d mod n
            sum %= pub_Key_First;
            decryptDone[j] = sum;
        }
 
    }
}

서버(공개키 생성 부분입니다)

//accept 
        CString str;
        CString ConnectInfo_str;
        CString ConnectInfo_str2;
 
        while (1)
        {
            //ACCEPT 
            enc.Selectpq();
            enc.SelectEulerETC();
            enc.SelectPriKey();
 
            tcpserver.ClntAccept();
            if (clnt_sock == SOCKET_ERROR)
            {
                break;
            }

서버(전송 부분 입니다)

    CServerDlg *dlg = (CServerDlg *)AfxGetApp()->m_pMainWnd;
    SOCKET socket = (SOCKET)p;
 
    char encPubKey_First[BUFSIZE];
    char encPubKey_Second[BUFSIZE];
    sprintf(encPubKey_First, "%u", enc.pub_Key_First);
    sprintf(encPubKey_Second, "%u", enc.pub_Key_Second);
    send(socket, encPubKey_First, sizeof(encPubKey_First), 0);
    while (1)
    {
        //recv
 
        tcpserver.ServRecv(socket); 
        if (tcpserver.recvsize <= 0) {
            break;
        }

RSA.h 입니다.
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include "ServerClass.h"
class Encryption
{
public:
    Encryption();
    ~Encryption();
    int sum = 1;
    int first;
    int second;
    int pub_Key_First; //n 공개기 및 개인키
    int eulerPi;
    int pub_Key_Second; //e 공개키
    int pri_Key; //d 개인키
 
    int decrypt;
    int word;
 
    char encrypt[BUFSIZE]; //BUFSIZE
    char encryptDone[BUFSIZE];
    char decryptDone[BUFSIZE];
 
    void Selectpq();
    void SelectEulerETC();
    void Enc(char buffer[], int bufsize);
    void Decryption(char buffer[], int bufsize);
    void SelectPriKey();
};
File attachments: 
첨부파일 크기
Image icon odCg9.png1.46 KB
l595659의 이미지

로그인도 안하고 올려서 게시글 중복 올린 것 삭제가 안되네요 죄송합니다.

peecky의 이미지

send(socket, encPubKey_First, sizeof(encPubKey_First), 0);

send()함수에서 보내려는 데이터의 길이보다 더 많은 데이터를 보내는 것 같습니다.

sizeof(encPubKey_First)의 값을 확인해보세요.

l595659의 이미지

데이터 길이보다 더 많아서 이상한 값이 떳던것 같네요 감사합니다!

익명 사용자의 이미지

pub_Key_Firstpub_Key_Second는 둘 다 int 입니다.

sprintf가 왜 필요하죠? send(socket, &enc.pub_Key_First, sizeof(enc.pub_Key_First), 0); 하면 되잖아요?

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.