VC++写的socket通信程序发送的信息用des加密然后在收到信息后解密

ZuoQiaQiaYin 2014-06-10 06:37:15
我是菜鸟额。]有一个简单的VC++写的socket通信程序,如何将发送的信息用des加密然后在收到信息后解密。求大神给个说明和des代码。
scoket服务器和客户端代码如下,如何加入des模块:
服务器端程序:

//sockServ.cpp
#include <iostream>
#include <Windows.h>
#pragma comment(lib, "WS2_32") // 链接到WS2_32.lib
using namespace std;

#define PORT 4000
//#define IP_ADDRESS "192.168.1.145"
#define IP_ADDRESS "127.0.0.1"

DWORD WINAPI ClientThread(LPVOID lpParameter)
{
SOCKET CientSocket = (SOCKET)lpParameter;
int Ret = 0;
char RecvBuffer[MAX_PATH];
char SendBuffer[MAX_PATH];

while ( true )
{
memset(RecvBuffer, 0x00, sizeof(RecvBuffer));
Ret = recv(CientSocket, RecvBuffer, MAX_PATH, 0);
if ( Ret == 0 || Ret == SOCKET_ERROR )
{
cout<<"客户端退出!"<<endl;
break;
}
cout<<"接收到客户信息为:"<<RecvBuffer<<endl;
//服务器端发送信息
cout<<"服务器端向客户端发送!:"<<endl;
cin.getline(SendBuffer, sizeof(SendBuffer));
Ret = send(CientSocket, SendBuffer, (int)strlen(SendBuffer), 0);
if ( Ret == SOCKET_ERROR )
{
cout<<"Send Info Error::"<<GetLastError()<<endl;
break;
}
}
return 0;
}

int main(int argc, char* argv[])
{
WSADATA Ws;
SOCKET ServerSocket, CientSocket;
struct sockaddr_in LocalAddr, ClientAddr;//sockaddr_in是TCP/IP使用的数据结构
int Ret = 0;
int AddrLen = 0;
HANDLE hThread = NULL;

//Init Windows Socket
if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )//socket使用2.2版本的
{
cout<<"Init Windows Socket Failed::"<<GetLastError()<<endl;
return -1;
}

ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
//ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( ServerSocket == INVALID_SOCKET )
{
cout<<"Create Socket Failed::"<<GetLastError()<<endl;
return -1;
}

LocalAddr.sin_family = AF_INET;//INTERNET协议簇
//LocalAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
LocalAddr.sin_addr.S_un.S_addr = INADDR_ANY;
LocalAddr.sin_port = htons(PORT);
memset(LocalAddr.sin_zero, 0x00, 8);

//Bind Socket
Ret = bind(ServerSocket, (struct sockaddr*)&LocalAddr, sizeof(LocalAddr));
if ( Ret != 0 )
{
cout<<"Bind Socket Failed::"<<GetLastError()<<endl;
return -1;
}

Ret = listen(ServerSocket, 10);//用ServerSocket来进行监听,监听最多10个客户端的请求
if ( Ret != 0 )
{
cout<<"listen Socket Failed::"<<GetLastError()<<endl;
return -1;
}

cout<<"服务端已经启动"<<endl;
while ( true )//因为是服务器端,要不停的监听客户端的请求
{
AddrLen = sizeof(ClientAddr);
//用CientSocket来进行通信
CientSocket = accept(ServerSocket, (struct sockaddr*)&ClientAddr, &AddrLen);
if ( CientSocket == INVALID_SOCKET )
{
cout<<"Accept Failed::"<<GetLastError()<<endl;
break;
}

cout<<"客户端连接::"<<inet_ntoa(ClientAddr.sin_addr)<<":"<<ClientAddr.sin_port<<endl;

hThread = CreateThread(NULL, 0, ClientThread, (LPVOID)CientSocket, 0, NULL);
if ( hThread == NULL )
{
cout<<"Create Thread Failed!"<<endl;
break;
}
CloseHandle(hThread);
}

closesocket(ServerSocket);
closesocket(CientSocket);
WSACleanup();

return 0;
}
客户端代码如下:
//sockCli.cpp
#include <iostream>
#include <Windows.h>
using namespace std;
#pragma comment(lib, "WS2_32") // 链接到WS2_32.lib

#define PORT 4000
//#define IP_ADDRESS "192.168.1.145"
#define IP_ADDRESS "127.0.0.1"

int main(int argc, char* argv[])
{
WSADATA Ws;
SOCKET CientSocket;
struct sockaddr_in ServerAddr;
int Ret = 0;
int AddrLen = 0;
HANDLE hThread = NULL;
char SendBuffer[MAX_PATH];
char RecvBuffer[MAX_PATH];

//Init Windows Socket
if ( WSAStartup(MAKEWORD(1,1), &Ws) != 0 )//客户端用的SOCKET库的版本和服务器端一样,就算不一样,也可以正常通信
{
cout<<"Init Windows Socket Failed::"<<GetLastError()<<endl;
return -1;
}

//Create Socket
CientSocket = socket(AF_INET, SOCK_STREAM, 0);//创建了一个客户端的SOCKET
if ( CientSocket == INVALID_SOCKET )
{
cout<<"Create Socket Failed::"<<GetLastError()<<endl;
return -1;
}

ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
ServerAddr.sin_port = htons(PORT);
memset(ServerAddr.sin_zero, 0x00, 8);
//连接到服务器,连接的服务器的地址在上面中设定
Ret = connect(CientSocket,(struct sockaddr*)&ServerAddr, sizeof(ServerAddr));
if ( Ret == SOCKET_ERROR )
{
cout<<"Connect Error::"<<GetLastError()<<endl;
return -1;
}
else
{
cout<<"连接成功!"<<endl;
}

while ( true )
{
cout<<"客户端,发送!:"<<endl;
cin.getline(SendBuffer, sizeof(SendBuffer));
//向服务器端发送数据
Ret = send(CientSocket, SendBuffer, (int)strlen(SendBuffer), 0);
if ( Ret == SOCKET_ERROR )
{
cout<<"Send Info Error::"<<GetLastError()<<endl;
break;
}
memset(RecvBuffer, 0x00, sizeof(RecvBuffer));
//从服务器端接收数据
Ret = recv(CientSocket, RecvBuffer, MAX_PATH, 0);
if ( Ret == 0 || Ret == SOCKET_ERROR )
{
cout<<"客户端退出!"<<endl;
break;
}
cout<<"接收到服务器信息为:"<<RecvBuffer<<endl;
}
closesocket(CientSocket);
WSACleanup();
return 0;
}
...全文
351 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2014-06-11
  • 打赏
  • 举报
回复
仅供参考
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "advapi32.lib")
#define _WIN32_WINNT 0x0400
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#define KEYLENGTH  0x00800000
void HandleError(char *s);
//--------------------------------------------------------------------
//  These additional #define statements are required.
#define ENCRYPT_ALGORITHM CALG_RC4
#define ENCRYPT_BLOCK_SIZE 8
//   Declare the function EncryptFile. The function definition
//   follows main.
BOOL EncryptFile(
    PCHAR szSource,
    PCHAR szDestination,
    PCHAR szPassword);
//--------------------------------------------------------------------
//   Begin main.
void main(void) {
    CHAR szSource[100];
    CHAR szDestination[100];
    CHAR szPassword[100];
    printf("Encrypt a file. \n\n");
    printf("Enter the name of the file to be encrypted: ");
    scanf("%s",szSource);
    printf("Enter the name of the output file: ");
    scanf("%s",szDestination);
    printf("Enter the password:");
    scanf("%s",szPassword);
    //--------------------------------------------------------------------
    // Call EncryptFile to do the actual encryption.
    if(EncryptFile(szSource, szDestination, szPassword)) {
        printf("Encryption of the file %s was a success. \n", szSource);
        printf("The encrypted data is in file %s.\n",szDestination);
    } else {
        HandleError("Error encrypting file!");
    }
} // End of main
//--------------------------------------------------------------------
//   Code for the function EncryptFile called by main.
static BOOL EncryptFile(
    PCHAR szSource,
    PCHAR szDestination,
    PCHAR szPassword)
//--------------------------------------------------------------------
//   Parameters passed are:
//     szSource, the name of the input, a plaintext file.
//     szDestination, the name of the output, an encrypted file to be
//         created.
//     szPassword, the password.
{
    //--------------------------------------------------------------------
    //   Declare and initialize local variables.
    FILE *hSource;
    FILE *hDestination;
    HCRYPTPROV hCryptProv;
    HCRYPTKEY hKey;
    HCRYPTHASH hHash;
    PBYTE pbBuffer;
    DWORD dwBlockLen;
    DWORD dwBufferLen;
    DWORD dwCount;
    //--------------------------------------------------------------------
    // Open source file.
    if(hSource = fopen(szSource,"rb")) {
        printf("The source plaintext file, %s, is open. \n", szSource);
    } else {
        HandleError("Error opening source plaintext file!");
    }
    //--------------------------------------------------------------------
    // Open destination file.
    if(hDestination = fopen(szDestination,"wb")) {
        printf("Destination file %s is open. \n", szDestination);
    } else {
        HandleError("Error opening destination ciphertext file!");
    }
    //以下获得一个CSP句柄
    if(CryptAcquireContext(
                &hCryptProv,
                NULL,               //NULL表示使用默认密钥容器,默认密钥容器名
                //为用户登陆名
                NULL,
                PROV_RSA_FULL,
                0)) {
        printf("A cryptographic provider has been acquired. \n");
    } else {
        if(CryptAcquireContext(
                    &hCryptProv,
                    NULL,
                    NULL,
                    PROV_RSA_FULL,
                    CRYPT_NEWKEYSET))//创建密钥容器
        {
            //创建密钥容器成功,并得到CSP句柄
            printf("A new key container has been created.\n");
        } else {
            HandleError("Could not create a new key container.\n");
        }
    }
    //--------------------------------------------------------------------
    // 创建一个会话密钥(session key)
    // 会话密钥也叫对称密钥,用于对称加密算法。
    // (注: 一个Session是指从调用函数CryptAcquireContext到调用函数
    //   CryptReleaseContext 期间的阶段。会话密钥只能存在于一个会话过程)
    //--------------------------------------------------------------------
    // Create a hash object.
    if(CryptCreateHash(
                hCryptProv,
                CALG_MD5,
                0,
                0,
                &hHash)) {
        printf("A hash object has been created. \n");
    } else {
        HandleError("Error during CryptCreateHash!\n");
    }
    //--------------------------------------------------------------------
    // 用输入的密码产生一个散列
    if(CryptHashData(
                hHash,
                (BYTE *)szPassword,
                strlen(szPassword),
                0)) {
        printf("The password has been added to the hash. \n");
    } else {
        HandleError("Error during CryptHashData. \n");
    }
    //--------------------------------------------------------------------
    // 通过散列生成会话密钥
    if(CryptDeriveKey(
                hCryptProv,
                ENCRYPT_ALGORITHM,
                hHash,
                KEYLENGTH,
                &hKey)) {
        printf("An encryption key is derived from the password hash. \n");
    } else {
        HandleError("Error during CryptDeriveKey!\n");
    }
    //--------------------------------------------------------------------
    // Destroy the hash object.
    CryptDestroyHash(hHash);
    hHash = NULL;
    //--------------------------------------------------------------------
    //  The session key is now ready.
    //--------------------------------------------------------------------
    // 因为加密算法是按ENCRYPT_BLOCK_SIZE 大小的块加密的,所以被加密的
    // 数据长度必须是ENCRYPT_BLOCK_SIZE 的整数倍。下面计算一次加密的
    // 数据长度。
    dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
    //--------------------------------------------------------------------
    // Determine the block size. If a block cipher is used,
    // it must have room for an extra block.
    if(ENCRYPT_BLOCK_SIZE > 1)
        dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
    else
        dwBufferLen = dwBlockLen;
    //--------------------------------------------------------------------
    // Allocate memory.
    if(pbBuffer = (BYTE *)malloc(dwBufferLen)) {
        printf("Memory has been allocated for the buffer. \n");
    } else {
        HandleError("Out of memory. \n");
    }
    //--------------------------------------------------------------------
    // In a do loop, encrypt the source file and write to the source file.
    do {
        //--------------------------------------------------------------------
        // Read up to dwBlockLen bytes from the source file.
        dwCount = fread(pbBuffer, 1, dwBlockLen, hSource);
        if(ferror(hSource)) {
            HandleError("Error reading plaintext!\n");
        }
        //--------------------------------------------------------------------
        // 加密数据
        if(!CryptEncrypt(
                    hKey,           //密钥
                    0,              //如果数据同时进行散列和加密,这里传入一个
                    //散列对象
                    feof(hSource),  //如果是最后一个被加密的块,输入TRUE.如果不是输.
                    //入FALSE这里通过判断是否到文件尾来决定是否为
                    //最后一块。
                    0,              //保留
                    pbBuffer,       //输入被加密数据,输出加密后的数据
                    &dwCount,       //输入被加密数据实际长度,输出加密后数据长度
                    dwBufferLen))   //pbBuffer的大小。
        {
            HandleError("Error during CryptEncrypt. \n");
        }
        //--------------------------------------------------------------------
        // Write data to the destination file.
        fwrite(pbBuffer, 1, dwCount, hDestination);
        if(ferror(hDestination)) {
            HandleError("Error writing ciphertext.");
        }
    } while(!feof(hSource));
    //--------------------------------------------------------------------
    //  End the do loop when the last block of the source file has been
    //  read, encrypted, and written to the destination file.
    //--------------------------------------------------------------------
    // Close files.
    if(hSource)
        fclose(hSource);
    if(hDestination)
        fclose(hDestination);
    //--------------------------------------------------------------------
    // Free memory.
    if(pbBuffer)
        free(pbBuffer);
    //--------------------------------------------------------------------
    // Destroy session key.
    if(hKey)
        CryptDestroyKey(hKey);
    //--------------------------------------------------------------------
    // Destroy hash object.
    if(hHash)
        CryptDestroyHash(hHash);
    //--------------------------------------------------------------------
    // Release provider handle.
    if(hCryptProv)
        CryptReleaseContext(hCryptProv, 0);
    return(TRUE);
} // End of Encryptfile
//--------------------------------------------------------------------
//  This example uses the function HandleError, a simple error
//  handling function, to print an error message to the standard error
//  (stderr) file and exit the program.
//  For most applications, replace this function with one
//  that does more extensive error reporting.
void HandleError(char *s) {
    fprintf(stderr,"An error occurred in running the program. \n");
    fprintf(stderr,"%s\n",s);
    fprintf(stderr, "Error number %x.\n", GetLastError());
    fprintf(stderr, "Program terminating. \n");
    exit(1);
} // End of HandleError

「已注销」 2014-06-11
  • 打赏
  • 举报
回复
这个是我之前收藏的一个可运行的des案今例,既然是收藏的,那当然是别人的东西,能正常运行 代码简洁,主要函数就一个加密与解密,你可直接用,自己封装到dll也行,下载链接:http://url.cn/KkkKnU,有问题再 留言

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧