반응형
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | using System; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.IO; namespace AsyncTest { public partial class Form1 : Form { private Socket clientSock; /* client Socket */ private Socket cbSock; /* client Async Callback Socket */ private byte[] recvBuffer; private const int MAXSIZE = 514; /* 4096 */ private string HOST = "xxx.xxx.xxx.xxx"; private int PORT = 123; private string Enter_key; private string recvString; public Form1() { InitializeComponent(); recvBuffer = new byte[MAXSIZE]; this.DoInit(); } //소켓 생성및 연결 public void DoInit() { clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.BeginConnect(); } /*----------------------* * Connection * *----------------------*/ public void BeginConnect() { tbDebug.Text = "서버 접속 대기 중"; try { clientSock.BeginConnect(HOST, PORT, new AsyncCallback(ConnectCallBack), clientSock); } catch (SocketException se) { /*서버 접속 실패 */ tbDebug.Text += "\r\n서버접속 실패하였습니다. " + se.NativeErrorCode; this.DoInit(); } } /*----------------------* * ##### CallBack ##### * * Connection * *----------------------*/ private void ConnectCallBack(IAsyncResult IAR) { try { // 보류중인 연결을 완성 Socket tempSock = (Socket)IAR.AsyncState; IPEndPoint svrEP = (IPEndPoint)tempSock.RemoteEndPoint; tbDebug.Text += "\r\n 서버로 접속 성공 : " + svrEP.Address; tempSock.EndConnect(IAR); cbSock = tempSock; cbSock.BeginReceive(this.recvBuffer, 0, recvBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), cbSock); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.NotConnected) { tbDebug.Text += "\r\n서버 접속 실패 CallBack " + se.Message; this.BeginConnect(); } } } /*----------------------* * Send * *----------------------*/ public void BeginSend(string message) { tbDebug.Text += "\r\n\r\n-------------- S E N D ----------------"; tbDebug.Text += "\r\n\r\nSEND DATA : " + message; try { /* 연결 성공시 */ if (clientSock.Connected) { //키보드를 통해 입력한 데이터를 암호화 한다. 뒤의 숫자는 암호화에 쓰일 key이다. string chiper = AES_encrypt(message, "01234567890123456789012345678901"); //데이터는 byte[]로 보내야하기 때문에 string -> byte byte[] buffer = Encoding.UTF8.GetBytes(chiper); //데이터 전송 clientSock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), chiper); } } catch (SocketException e) { tbDebug.Text = "\r\n\r\n전송 에러 : " + e.Message; } } /*----------------------* * ##### CallBack ##### * * Send * *----------------------*/ private void SendCallBack(IAsyncResult IAR) { string message = (string)IAR.AsyncState; //데이터 전송에 있어서 공백이 '\0'로 채워질수 있기 때문에 이를 방지하기위해 trim() 함수를 사용한다. message = message.Trim('\0'); tbDebug.Text += "\r\n\r\nBASE64ENCODING ( AES256 ( SEND DATA ) ) : " + message; } /*----------------------* * Receive * *----------------------*/ public void Receive() { cbSock.BeginReceive(this.recvBuffer, 0, recvBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), cbSock); } /*----------------------* * ##### CallBack ##### * * Receive * *----------------------*/ private void OnReceiveCallBack(IAsyncResult IAR) { try { Socket tempSock = (Socket)IAR.AsyncState; int nReadSize = tempSock.EndReceive(IAR); if (nReadSize != 0) { tbDebug.Text += "\r\n\r\n-------------- R E C E I V E -------------"; //수신받은 데이터의 나머지부분이 '\0'로 채워진다. //그렇게 되면 복호화가 되지않기 때문에 trim() 함수를 사용하여 제거한다. recvString = Encoding.UTF8.GetString(recvBuffer).Trim('\0'); Array.Clear(recvBuffer, 0, recvBuffer.Length); tbDebug.Text += "\r\n\r\nBASE64ENCODING ( AES256 ( RECEIVE DATA ) ) : " + recvString; //복호화 string chiper = AES_decrypt(recvString, "01234567890123456789012345678901"); this.tbDebug.Text += "\r\n\r\nRECEIVE DATA : " + chiper; } this.Receive(); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.ConnectionReset) { this.BeginConnect(); } } } //AES256 암호화 public String AES_encrypt(String Input, String key) { RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = Encoding.UTF8.GetBytes("0123456789012345"); var encrypt = aes.CreateEncryptor(aes.Key, aes.IV); byte[] xBuff = null; using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) { byte[] xXml = Encoding.UTF8.GetBytes(Input); cs.Write(xXml, 0, xXml.Length); } xBuff = ms.ToArray(); string recvdata = Encoding.Default.GetString(xBuff); tbDebug.Text += "\r\n\r\nAES256 ( SEND DATA ) : " + recvdata; } string Output = Convert.ToBase64String(xBuff); return Output; } //AES 256 복호화 public string AES_decrypt(string Input, string key) { RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = Encoding.UTF8.GetBytes("0123456789012345"); var decrypt = aes.CreateDecryptor(); byte[] xBuff = null; using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write)) { byte[] xXml = Convert.FromBase64String(Input); string recvdata = Encoding.Default.GetString(xXml); tbDebug.Text += "\r\n\r\nAES256 ( RECEIVE DATA ) : " + recvdata; cs.Write(xXml, 0, xXml.Length); } xBuff = ms.ToArray(); } string Output = Encoding.UTF8.GetString(xBuff); return Output; } private void Form1_Load(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { Enter_key = textBox1.Text; } private void button1_Click(object sender, EventArgs e) { if (Enter_key != "") { this.BeginSend(Enter_key); textBox1.Text = ""; } } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { button1_Click(sender, e); } } } } | cs |
c#으로 코드가 이루어져 있으며 base64 Encoding,Decoding 과 aes256 암복호화를 통해 통신을 한다.
http://www.imcore.net/encryption-aes256-c-objectivec-ios-iphone-ipad-php-java-android-perl-javascript-python/
위에분의 블로그가 없었다면 암복호화에 엄청난 애를 먹었을 것이다.
Form안에 들어가는 내용이며 전체적인 소스코드는 올리지 않았다.
동작화면은 아래와 같다.
반응형
'나는요 공부가 좋....은걸... > 암호화 + 소켓통신' 카테고리의 다른 글
C 소켓프로그래밍 (양방향 통신[Server]) + 암호화(AES256, base64) (0) | 2017.12.14 |
---|