首页主机资讯Linux C++如何实现数据加密解密

Linux C++如何实现数据加密解密

时间2025-12-09 14:10:03发布访客分类主机资讯浏览1399
导读:在Linux环境下使用C++进行数据加密和解密,通常会借助一些加密库,比如OpenSSL。以下是使用OpenSSL库进行AES加密和解密的一个基本示例。 首先,确保你的Linux系统上安装了OpenSSL库。如果没有安装,可以使用以下命令安...

在Linux环境下使用C++进行数据加密和解密,通常会借助一些加密库,比如OpenSSL。以下是使用OpenSSL库进行AES加密和解密的一个基本示例。

首先,确保你的Linux系统上安装了OpenSSL库。如果没有安装,可以使用以下命令安装:

sudo apt-get update
sudo apt-get install libssl-dev

然后,你可以编写一个C++程序来实现AES加密和解密。以下是一个简单的示例代码:

#include <
    iostream>
    
#include <
    openssl/aes.h>
    
#include <
    openssl/rand.h>
    
#include <
    cstring>
    

// 加密函数
std::string aes_encrypt(const std::string&
     plain_text, const std::string&
 key) {
    
    AES_KEY enc_key;
    
    AES_set_encrypt_key(reinterpret_cast<
    const unsigned char*>
    (key.c_str()), 256, &
    enc_key);
    

    // 加密后的数据大小会是明文大小的16字节对齐,所以需要分配足够的空间
    std::string cipher_text(plain_text.size() + AES_BLOCK_SIZE, '\0');
    

    AES_encrypt(reinterpret_cast<
    const unsigned char*>
    (plain_text.c_str()),
                reinterpret_cast<
    unsigned char*>
    (&
    cipher_text[0]),
                &
    enc_key);
    

    return cipher_text;

}
    

// 解密函数
std::string aes_decrypt(const std::string&
     cipher_text, const std::string&
 key) {
    
    AES_KEY dec_key;
    
    AES_set_decrypt_key(reinterpret_cast<
    const unsigned char*>
    (key.c_str()), 256, &
    dec_key);
    

    // 解密后的数据大小应该和明文大小相同
    std::string plain_text(cipher_text.size(), '\0');
    

    AES_decrypt(reinterpret_cast<
    const unsigned char*>
    (cipher_text.c_str()),
                reinterpret_cast<
    unsigned char*>
    (&
    plain_text[0]),
                &
    dec_key);
    

    return plain_text;

}


int main() {
    
    std::string original_text = "Hello, World!";
    
    std::string key = "0123456789abcdef0123456789abcdef";
     // 256-bit key

    // 加密
    std::string encrypted_text = aes_encrypt(original_text, key);
    
    std::cout <
    <
     "Encrypted text: ";

    for (char c : encrypted_text) {
    
        printf("%x", c);

    }
    
    std::cout <
    <
     std::endl;
    

    // 解密
    std::string decrypted_text = aes_decrypt(encrypted_text, key);
    
    std::cout <
    <
     "Decrypted text: " <
    <
     decrypted_text <
    <
     std::endl;
    

    return 0;

}
    

编译这个程序,你需要链接OpenSSL的加密库:

g++ -o aes_example aes_example.cpp -lcrypto

运行编译后的程序:

./aes_example

请注意,这个示例使用了AES-256位加密,密钥长度必须是16、24或32字节。在实际应用中,你需要确保密钥的安全管理,并且妥善处理加密后的数据,比如进行适当的填充和编码,以便安全地存储或传输。

此外,加密和解密操作可能会失败,因此在生产代码中应该添加错误检查和处理逻辑。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Linux C++如何实现数据加密解密
本文地址: https://pptw.com/jishu/767088.html
Debian和Sedebian安全性有何差异 C++在Linux中如何进行图形界面编程

游客 回复需填写必要信息