亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

如何在C++中實現buffer的加密解密功能

c++
小樊
81
2024-08-07 20:03:25
欄目: 編程語言

在C++中實現buffer的加密解密功能通常使用加密算法庫,例如OpenSSL或Crypto++。以下是一個使用OpenSSL庫實現buffer的加密解密功能的示例代碼:

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

void encryptBuffer(const unsigned char* buffer, size_t bufferSize, const unsigned char* key, const unsigned char* iv, unsigned char* encryptedBuffer) {
    EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
    EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);

    int len;
    int encryptedSize;

    EVP_EncryptUpdate(ctx, encryptedBuffer, &len, buffer, bufferSize);
    encryptedSize = len;

    EVP_EncryptFinal_ex(ctx, encryptedBuffer + len, &len);
    encryptedSize += len;

    EVP_CIPHER_CTX_free(ctx);
}

void decryptBuffer(const unsigned char* encryptedBuffer, size_t encryptedBufferSize, const unsigned char* key, const unsigned char* iv, unsigned char* decryptedBuffer) {
    EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
    EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);

    int len;
    int decryptedSize;

    EVP_DecryptUpdate(ctx, decryptedBuffer, &len, encryptedBuffer, encryptedBufferSize);
    decryptedSize = len;

    EVP_DecryptFinal_ex(ctx, decryptedBuffer + len, &len);
    decryptedSize += len;

    EVP_CIPHER_CTX_free(ctx);
}

int main() {
    unsigned char key[] = "0123456789abcdef";
    unsigned char iv[] = "abcdefghijklmnop";

    unsigned char buffer[] = "Hello, world!";
    size_t bufferSize = strlen((const char*)buffer);
    size_t encryptedBufferSize = bufferSize + AES_BLOCK_SIZE;

    unsigned char encryptedBuffer[encryptedBufferSize];
    unsigned char decryptedBuffer[bufferSize];

    encryptBuffer(buffer, bufferSize, key, iv, encryptedBuffer);
    decryptBuffer(encryptedBuffer, encryptedBufferSize, key, iv, decryptedBuffer);

    decryptedBuffer[bufferSize] = '\0';
    printf("Decrypted buffer: %s\n", decryptedBuffer);

    return 0;
}

在這個示例中,我們使用AES加密算法對buffer進行加密和解密。首先使用encryptBuffer函數對buffer進行加密,然后使用decryptBuffer函數對加密后的buffer進行解密。在主函數中,我們提供了一個簡單的測試,對加密后的buffer進行解密并輸出結果。

0
龙江县| 台东市| 确山县| 溆浦县| 吴川市| 抚松县| 山阳县| 湖南省| 东丰县| 浦北县| 卢龙县| 扬中市| 华宁县| 礼泉县| 抚州市| 康乐县| 任丘市| 华安县| 南宁市| 资源县| 长沙市| 阿坝县| 昭平县| 龙陵县| 沐川县| 甘孜县| 固始县| 苍南县| 曲周县| 杂多县| 盈江县| 开封县| 宽城| 怀集县| 大连市| 东光县| 营山县| 五常市| 湖北省| 台北市| 肇东市|