加密不定长数据 且 加密前数据和加密后数据大小相等, <已解决:RC4算法可以实现>

AYZRxx 2017-08-15 04:31:41
1. 我使用的是OpenSSL库, AES算法
2. 想实现的功能是加密不定长的数据, 而且加密后的数据和原始数据一样大
求个能实现的算法, 求简单的, 本人基本上学过过算法

3. 比如加密下面这20个字节数据, 数据就被加密成32个字节的数据, 数据变大了
BYTE byIn[20 = {
'\x11' ,'\x22' ,'\x33' ,'\x44' ,'\x55' ,'\x66' ,'\x77' ,'\x88' ,
'\x99' ,'\xAA' ,'\x00' ,'\xCC' ,'\xDD' ,'\xEE' ,'\xFF' ,'\x00' ,
'\x45' ,'\x4A' ,'\x05' ,'\x8C' //加密之后变成了16个字节的加密数据
};


4. 下面是代码, 解密之后最后一块数据<20个字节的后4个字节不对了>, 因为AES是按照16个字节加密解密的
#include "stdafx.h"
#include <openssl/ssl.h>
#include <openssl/aes.h>
#include <openssl/rsa.h>
#include <openssl/rc4.h>

#include <string>
#include <iostream>
#include <fstream>
#include <PeClass.h>
using std::string;

//AES加密是以每组16个字节加密的
//AES加密(加密后数据, 加密前数据, 大小, 密钥)
void AesEncryption(OUT BYTE* bOutData, IN BYTE* bInData, IN DWORD dwSizeOut, OUT string strKey)
{
DWORD dwSize = Align(dwSizeOut, 16);

//new一片0x16对齐后的空间
BYTE* byNewIn = new BYTE[dwSize]();
memcpy(byNewIn, bInData, dwSizeOut);

//计算加密的次数
DWORD dwAlignNum = dwSizeOut / 16;

//最后一块剩余字节数
DWORD dwRemain = dwSizeOut % 16 ;

if (dwRemain)
{
++dwAlignNum;;
}

unsigned char aes_keybuf[32] = { 0 };
//memset(aes_keybuf,0,sizeof(aes_keybuf));
//将密钥复制到aes_keybuf
strcpy((char *)aes_keybuf, strKey.c_str());
//把明文密钥加密处理
AES_KEY aeskey;
AES_set_encrypt_key(aes_keybuf, 256, &aeskey);


//new一片0x16对齐后的空间
BYTE* byNewOut = new BYTE[dwSize]();


for (DWORD i = 0; i < dwAlignNum; i++)
{
AES_encrypt((const unsigned char *) ((DWORD)byNewIn + i * 16),
(unsigned char *) ((DWORD)byNewOut + i * 16),
&aeskey);
}


//把实际加密后数据, 复制到输出缓冲区
memcpy(bOutData, byNewOut, dwSizeOut);


delete byNewOut;
delete byNewIn;
}


//AES解密(解密后数据, 解密前数据, 大小, 密钥)
void AesDecryption(OUT BYTE* bOutData, IN BYTE* bInData, IN DWORD dwSizeOut, OUT string strKey)
{
DWORD dwSize = Align(dwSizeOut, 16);

//new一片0x16对齐后的空间
BYTE* byNewIn = new BYTE[dwSize]();
memcpy(byNewIn, bInData, dwSizeOut);

//计算加密的次数
DWORD dwAlignNum = dwSizeOut / 16;

//最后一块剩余字节数
DWORD dwRemain = dwSizeOut % 16;

if (dwRemain)
{
++dwAlignNum;;
}

unsigned char aes_keybuf[32] = { 0 };
//memset(aes_keybuf,0,sizeof(aes_keybuf));
//将密钥复制到aes_keybuf
strcpy((char *)aes_keybuf, strKey.c_str());
//把明文密钥加密处理
AES_KEY aeskey;
AES_set_decrypt_key(aes_keybuf, 256, &aeskey);


//new一片0x16对齐后的空间
BYTE* byNewOut = new BYTE[dwSize]();


for (DWORD i = 0; i < dwAlignNum; i++)
{
AES_decrypt((const unsigned char *)((DWORD)byNewIn + i * 16),
(unsigned char *)((DWORD)byNewOut + i * 16),
&aeskey);
}


//把实际加密后数据, 复制到输出缓冲区
memcpy(bOutData, byNewOut, dwSizeOut);

delete byNewOut;
delete byNewIn;
}


BYTE byIn[20] = {
'\x11' ,'\x22' ,'\x33' ,'\x44' ,'\x55' ,'\x66' ,'\x77' ,'\x88' ,
'\x99' ,'\xAA' ,'\x00' ,'\xCC' ,'\xDD' ,'\xEE' ,'\xFF' ,'\x00' ,
'\x45' ,'\x4A' ,'\x05' ,'\x8C'
};

int main(void) {

//BYTE byIn[20] = {};
BYTE byOut[20] = {};
BYTE byBuf[20] = {};

AesEncryption(byOut, byIn, 20, "123456");

AesDecryption(byBuf, byOut, 20, "123456");

return 0;
}
...全文
3887 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2017-08-15
  • 打赏
  • 举报
回复
仅供参考:
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "advapi32.lib")
#define _WIN32_WINNT 0x0400
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#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 destination 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

RAR 是一个让你在命令行模式中管理压缩文件的控制台应用。RAR 提供压缩、加 密、数据恢复和许多其它此手册中描述的其它功能。 RAR 只支持 RAR 格式压缩文件,它默认有 .rar 扩展名。不支持ZIP 和其他格 式。即使创建压缩文件时指定了 .zip 扩展名,它仍然是 RAR 格式的。Windows 用户 可以 WinRAR,它支持更多的压缩文件类型,包括 RAR 和 ZIP 格式。 WinRAR 提供了图形用户界面和命令行模式。虽然控制台 RAR 和图形界面 WinRAR 有相似的命令行语法,但是它们还有有一些不同。所以推荐使用此 rar.txt 手册用于 控制台 RAR(rar.exe 在 Windows 版本的情况下),winrar.chm 是图形界面 WinRAR (winrar.exe) 的帮助文件。 配置文件 ~~~~~~~~ Unix 版本的 RAR 从用户的 home 或 /etc 目录中的 .rarrc 文件读取配置文件信息 (存储在 HOME 环境变量中) Windows 的版本 RAR 从 rar.ini 文件读取配置文件信息,它放在 rar.exe 文件相 同的目录中。 这个文件包含下列字符串: switches=任何 RAR 开关,用空格分开 例如: switches=-m5 -s 环境变量 ~~~~~~~~ 可以通过建立"RAR"环境变量来添加默认参数到命令行中. 例如,在 Unix 中,下列命令行可以被添加到你的配置中: RAR='-s -md1024' export RAR RAR 将使用这个字符串作为命令行的默认参数,并将使用 1024KB 字典大小来创建 “固实”压缩文件。 RAR 控制选项使用下列优先级: 命名行开关 最高优先级 在 RAR 变量中的开关 低优先级 保存在配置文件中的开关 最低优先级 日志文件 ~~~~~~~~ 如果在命令行或配置文件中指定开关 -ilog ,RAR 将会把处理压缩文件中遇到的错误 等写到日志文件中。读取开关 -ilog 描述获得更多信息。 固实压缩的文件列表 - rarfiles.lst ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rarfiles.lst 包含一个用户定义的文件列表,告诉 RAR 添加文件到固实压缩文件时的顺 序。它可以包含文件名通配符和指定项目 -$default。默认项目定义了这个文件中与 其他项目不相符时的顺序清单位置。 注释字符是 ';'. 在 Windows 中,这个文件应该放在 RAR 所在的或 %APPDATA%\WinRAR 目录中, 在 Unix 中- 放在用户的 home 目录或在 /etc 中。 提高压缩率和操作速度的提示: - 在压缩文件中,小文件应该被组织在一起; - 频繁被处理的文件应该放在开始的位置。 普通的掩码越靠近顶端优先权就越高,但是这个规则存在例外。如果 rarfiles.lst 包含两个掩码,并且所有文件既匹配第一个掩码,也匹配第二个掩码, 较小的子集 或者更精确的匹配拥有更高的优先权。例如,如果你用 *.cpp 和 f*.cpp 掩码, f*.cpp 拥有更高的优先权。 RAR 命令行语法 ~~~~~~~~~~~~~~ 语法 RAR [ - ] [ ] [ ] [ ] 描述 命令行选项 (命令和开关) 提供了使用 RAR 创建和管理压缩文件的控制方法。命 令是一个字符串(或单个的字母),命令 RAR 去执行一个相应的操作。开关被用来 改变 RAR 执行操作的方法。其它参数是压缩文件名和被压缩的文件或要从压缩文件 中被解压文件。 列表文件是一个包括处理的文件名的纯文本文件。第一列应该以文件名开始。可以 在//字符后添加注释。例如,你可以创建包含下列字符串的 backup.lst: c:\work\doc\*.txt //备份文本文档 c:\work\image\*.bmp //备份图片 c:\

5,530

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 模式及实现
社区管理员
  • 模式及实现社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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