c++ openssl 加密内存中的一段内容并解密这段内容

创建日期: 2023-06-13 17:55 | 作者: 风波 | 浏览次数: 14 | 分类: C++

来源:chatGPT

#include <iostream>
#include <openssl/evp.h>

void encryptMemory(const unsigned char* plaintext, size_t plaintextSize, const unsigned char* key, const unsigned char* iv,
                   unsigned char* ciphertext, size_t& ciphertextSize) {
    EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();

    EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, iv);
    EVP_EncryptUpdate(ctx, ciphertext, reinterpret_cast<int*>(&ciphertextSize), plaintext, static_cast<int>(plaintextSize));
    EVP_EncryptFinal_ex(ctx, ciphertext + ciphertextSize, reinterpret_cast<int*>(&ciphertextSize));

    EVP_CIPHER_CTX_free(ctx);
}

void decryptMemory(const unsigned char* ciphertext, size_t ciphertextSize, const unsigned char* key, const unsigned char* iv,
                   unsigned char* plaintext, size_t& plaintextSize) {
    EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();

    EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, iv);
    EVP_DecryptUpdate(ctx, plaintext, reinterpret_cast<int*>(&plaintextSize), ciphertext, static_cast<int>(ciphertextSize));
    EVP_DecryptFinal_ex(ctx, plaintext + plaintextSize, reinterpret_cast<int*>(&plaintextSize));

    EVP_CIPHER_CTX_free(ctx);
}

int main() {
    // 假设有要加密的内存块
    const unsigned char plaintext[] = "Hello, World!";
    size_t plaintextSize = sizeof(plaintext) - 1;  // 不包括结尾的'\0'

    // 定义密钥和初始化向量(IV)
    const unsigned char key[] = "01234567890123456789012345678901";  // 256位密钥
    const unsigned char iv[] = "0123456789012345";  // 128位IV

    // 计算加密后的密文大小
    size_t ciphertextSize = plaintextSize + EVP_MAX_BLOCK_LENGTH;  // 设置足够的空间

    // 分配内存用于存储密文
    unsigned char* ciphertext = new unsigned char[ciphertextSize];

    // 加密内存中的内容
    encryptMemory(plaintext, plaintextSize, key, iv, ciphertext, ciphertextSize);

    // 输出加密后的密文
    std::cout << "Ciphertext: ";
    for (size_t i = 0; i < ciphertextSize; i++) {
        std::cout << std::hex << static_cast<int>(ciphertext[i]);
    }
    std::cout << std::endl;

    // 分配内存用于存储解密后的明文
    unsigned char* decryptedText = new unsigned char[plaintextSize];

    // 解密密文
    size_t decryptedTextSize = 0;
    decryptMemory(ciphertext, ciphertextSize, key, iv, decryptedText, decryptedTextSize);

    // 输出解密后的明文
    std::cout << "Decrypted text: " << decryptedText << std::endl;

    // 释放内存
    delete[] ciphertext;
    delete[] decryptedText;

    return 0;
}
14 浏览
9 爬虫
0 评论