以下是使用 Crypto++ 库在 CodeBlocks 下用 mingw 编译器调用 AES 加密的 C 语言代码示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/filters.h>

int main() {
    // 定义 AES 密钥和初始向量
    byte key[CryptoPP::AES::DEFAULT_KEYLENGTH] = '0123456789abcdef';
    byte iv[CryptoPP::AES::BLOCKSIZE] = 'aaaaaaaaaaaaaaaa';

    // 定义要加密的明文
    const char* plaintext = 'Hello, World!';
    size_t plaintextLength = strlen(plaintext) + 1;

    // 定义加密后的密文
    byte ciphertext[1024];

    try {
        // 创建 AES 加密器
        CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
        
        // 使用 CBC 模式,设置初始向量
        CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, iv);

        // 使用 StreamTransformationFilter 进行加密
        CryptoPP::StreamTransformationFilter encryptor(cbcEncryption, new CryptoPP::ArraySink(ciphertext, plaintextLength));

        // 执行加密操作
        encryptor.Put(reinterpret_cast<const unsigned char*>(plaintext), plaintextLength);
        encryptor.MessageEnd();

        // 输出加密后的密文
        printf('Ciphertext: ');
        for (size_t i = 0; i < plaintextLength; ++i) {
            printf('%02x', ciphertext[i]);
        }
        printf('
');
    } catch (const CryptoPP::Exception& e) {
        fprintf(stderr, 'CryptoPP exception: %s
', e.what());
        return 1;
    }

    return 0;
}

请确保已正确安装 Crypto++ 库,并在 CodeBlocks 的项目设置中添加正确的包含目录和库目录。编译运行后,将输出加密后的密文。

重要说明:

  • 以上示例代码仅供学习和参考,实际应用中建议使用更安全的密钥生成和管理方法。
  • 确保使用强密码,不要使用容易猜到的密钥。
  • 密钥和初始向量应严格保密,不要泄露给任何人。
  • 使用加密库时,务必仔细阅读官方文档,并遵循安全规范。
  • 本文仅供参考,如有任何问题,请咨询相关专家。
CodeBlocks 使用 MinGW 和 Crypto++ 库进行 AES 加密:C 语言示例

原文地址: https://www.cveoy.top/t/topic/qd8Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录