内存中的unsigned char加密

问题描述 投票:0回答:1

我正在尝试使用Crypto ++在AES256的内存文件中创建字节数组加密/解密。

我需要加密一个unsigned char字节数组,并将加密数据作为unsigned char字节数组获取!解密也是如此。

我尝试了很多我在网上找到的解决方案,但我无法让它发挥作用。输出文件和长度是错误的。

我怎样才能使它工作?


block_aes.h:

const unsigned char original_Data[42] = {
    0x54, 0x48, 0x49, 0x53, 0x20, 0x49, 0x53, 0x20, 0x54, 0x45, 0x53, 0x54,
    0x20, 0x44, 0x41, 0x54, 0x41, 0x20, 0x49, 0x54, 0x20, 0x43, 0x41, 0x4E,
    0x20, 0x42, 0x45, 0x20, 0x41, 0x4E, 0x59, 0x20, 0x46, 0x49, 0x4C, 0x45,
    0x20, 0x44, 0x41, 0x54, 0x41, 0x2E
};

const unsigned char iv[16] = {
    0xAE, 0x50, 0x95, 0xEB, 0xC5, 0x76, 0x20, 0x1A, 0xA4, 0x84, 0xB6, 0xB0,
    0x51, 0x03, 0xEE, 0xE8
};

const unsigned char key[32] = {
    0xDA, 0x1F, 0x84, 0x85, 0xBD, 0x62, 0x2D, 0xB1, 0x45, 0x13, 0x84, 0x20,
    0xCF, 0x02, 0x47, 0xB9, 0x85, 0xEC, 0x78, 0xD7, 0x85, 0xEF, 0x07, 0xD7,
    0xA8, 0x15, 0x11, 0x6E, 0x11, 0xDF, 0xEE, 0x39
};

block_aes.cpp:

int _tmain(int argc, _TCHAR* argv[])
{
    /// Encrypt
    vector<CryptoPP::byte> cipher;

    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

    cipher.resize(sizeof(original_Data)+AES::BLOCKSIZE);
    ArraySink cs(&cipher[0], cipher.size());

    ArraySource(original_Data,sizeof(original_Data), true,
        new StreamTransformationFilter(enc, new Redirector(cs)));
    cipher.resize(cs.TotalPutLength());

    /// Test
    DWORD tmp;
    HANDLE File_Out = CreateFileA(
        "Encrypted.File",
        GENERIC_ALL,
        FILE_SHARE_WRITE,
        NULL,
        CREATE_NEW,
        FILE_ATTRIBUTE_NORMAL,
        &tmp
    );

    WriteFile(File_Out, &cipher, sizeof(cipher), &tmp, NULL);

    /// Decrypt
    vector<CryptoPP::byte> recover;
    CBC_Mode<AES>::Decryption dec;
    dec.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

    recover.resize(cipher.size());
    ArraySink rs(&recover[0], recover.size());

    ArraySource(cipher.data(), cipher.size(), true,
        new StreamTransformationFilter(dec, new Redirector(rs)));

    recover.resize(rs.TotalPutLength());

    /// Test    
    HANDLE File_Out2 = CreateFileA(
        "Decrypted.File",
        GENERIC_ALL,
        FILE_SHARE_WRITE,
        NULL,
        CREATE_NEW,
        FILE_ATTRIBUTE_NORMAL,
        &tmp
    );

    WriteFile(File_Out2, &recover, sizeof(recover), &tmp, NULL);
}
c++ windows encryption crypto++
1个回答
1
投票

在你的WriteFile调用中,你写出cipher变量的内容,而不是存储在向量中的内容。要保存您需要的矢量

WriteFile(File_Out, cipher.data(), cipher.size(), &tmp, NULL);

和:

WriteFile(File_Out2, recover.data(), recover.size(), &tmp, NULL);

既然你使用了address-of运算符,这里有另一种写法:

WriteFile(File_Out, &cipher[0], cipher.size(), &tmp, NULL);

&cipher[0]是在C ++ 03和C ++ 11中获取非const指针(可写)的唯一方法。 (但是你不需要它,因为const指针(可读)工作正常)。

© www.soinside.com 2019 - 2024. All rights reserved.