c++使用openssl静态库 实现AES 分片加密 解密

本文是在windows环境下,使用的是vs2019编译器。

下面是使用openssl静态库中的函数 实现的一个AES加密字符串以及加密文件。

下面展示一些 本人实现代码

#include
#include  
#include "Iphlpapi.h" 
#include
#include 


using namespace std;
#pragma comment(lib,"Iphlpapi.lib")
#pragma comment(lib,"libcrypto.lib")
#pragma comment(lib,"libssl.lib")


#include 
#include 
#include 
#include 
#include 

//分块加密
vector AesEncrypt(const unsigned char* userKey, const unsigned char* in, AES_KEY &aes)
{
    int result = AES_set_encrypt_key((const unsigned char*)userKey, 128, &aes);//设置加密密钥
    if (result < 0)//如果设置失败,退出
        //return ;

    printf("in=%s\n", in);

    vector outdata;
    printf("out=");
    for (int i = 0; i < strlen((const char*)in) / 16 + 1; i++)
    {
        unsigned char* out = (unsigned char*)malloc(sizeof(unsigned char) * 17);
        AES_ecb_encrypt((const unsigned char*)in + 16 * i, out, &aes, AES_ENCRYPT);
        printf("%s", out);//输出密文
        outdata.push_back(out);
    }
    printf("\n");

    return outdata;
}
//分块解密
void AesDecrypt(const unsigned char* userKey, AES_KEY &aes, vector outdata)
{
    if (AES_set_decrypt_key((const unsigned char*)userKey, 128, &aes) < 0)
        return ;
    unsigned char* plain = (unsigned char*)malloc(sizeof(unsigned char) * 17);
    printf("plain=");
    for (int i = 0; i < outdata.size(); i++)
    {
        memset((void*)plain, 0, 17);
        AES_ecb_encrypt(outdata.at(i), plain, &aes, AES_DECRYPT);
        printf("%s", plain);//输出解密后的明文
    }
    printf("\n");
}

CHAR* OpenFile()
{
    CHAR* pBuffer;
    DWORD RSize;
    int fileSize = 0;
    HANDLE hOpenFile = (HANDLE)CreateFile(L"D:\\a.txt", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
    if (hOpenFile == INVALID_HANDLE_VALUE)
    {
        hOpenFile = NULL;
        MessageBoxA(NULL, "Can not open the file", "Playwav", MB_OK);
        exit(1);
    }
    fileSize = GetFileSize(hOpenFile, NULL);
    pBuffer = (CHAR*)malloc(fileSize);
    ReadFile(hOpenFile, pBuffer, fileSize, &RSize, NULL);
    //可将pBuffer显示在某区域或写入另一个文件来检查读出是否正确

    FlushFileBuffers(hOpenFile);
    CloseHandle(hOpenFile);
    return pBuffer;
}

int main(int argc, char* argv[])
{
    AES_KEY aes;

    const  char* userKey = "Hello,World!!";
    char* puffer = OpenFile();
    vector outdata = AesEncrypt((const unsigned char*)userKey, (const unsigned char*)puffer, aes);  //加密
    AesDecrypt((const unsigned char*)userKey, aes, outdata);  //解密

    system("pause");

}

感谢大家观看 同时如果发现问题 希望指出 大家一起进步

你可能感兴趣的:(c++,windows,openssl,c++,windows)