linux

C++如何在Linux中进行数据加密

小樊
45
2025-08-26 05:04:38
栏目: 编程语言

在Linux中,可以使用OpenSSL库进行数据加密。OpenSSL是一个强大的加密工具包,提供了多种加密算法,如AES、DES、RSA等。以下是一个简单的示例,展示了如何使用OpenSSL库进行AES加密和解密。

首先,确保已经安装了OpenSSL库。在大多数Linux发行版中,可以使用以下命令安装:

sudo apt-get install libssl-dev

接下来,创建一个名为aes_encryption.cpp的C++文件,并添加以下代码:

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

std::string aes_encrypt(const std::string &plaintext, const std::string &key) {
    AES_KEY enc_key;
    AES_set_encrypt_key(reinterpret_cast<const unsigned char *>(key.c_str()), 256, &enc_key);

    int len = plaintext.size();
    int ciphertext_len = len + AES_BLOCK_SIZE;
    std::string ciphertext(ciphertext_len, '\0');

    AES_cbc_encrypt(reinterpret_cast<const unsigned char *>(plaintext.c_str()), reinterpret_cast<unsigned char *>(&ciphertext[0]), len, &enc_key, reinterpret_cast<unsigned char *>(&ciphertext[0]), AES_ENCRYPT);

    return ciphertext;
}

std::string aes_decrypt(const std::string &ciphertext, const std::string &key) {
    AES_KEY dec_key;
    AES_set_decrypt_key(reinterpret_cast<const unsigned char *>(key.c_str()), 256, &dec_key);

    int len = ciphertext.size();
    int plaintext_len = len - AES_BLOCK_SIZE;
    std::string plaintext(plaintext_len, '\0');

    AES_cbc_encrypt(reinterpret_cast<const unsigned char *>(ciphertext.c_str()), reinterpret_cast<unsigned char *>(&plaintext[0]), len, &dec_key, reinterpret_cast<unsigned char *>(&plaintext[0]), AES_DECRYPT);

    return plaintext;
}

int main() {
    std::string plaintext = "Hello, World!";
    std::string key = "thisisaeskey123";

    std::string encrypted = aes_encrypt(plaintext, key);
    std::cout << "Encrypted: ";
    for (char c : encrypted) {
        std::cout << std::hex << (int)c;
    }
    std::cout << std::endl;

    std::string decrypted = aes_decrypt(encrypted, key);
    std::cout << "Decrypted: " << decrypted << std::endl;

    return 0;
}

编译并运行代码:

g++ -o aes_encryption aes_encryption.cpp -lcrypto
./aes_encryption

这个示例使用了AES-256-CBC加密算法。在实际应用中,可以根据需要选择其他加密算法。注意,密钥长度应与所选加密算法相匹配。

对于RSA加密,可以使用OpenSSL的PEM_read_RSA_PUBKEY和PEM_write_RSAPublicKey函数进行公钥加密和私钥解密。更多关于OpenSSL库的使用方法,请参考官方文档:https://www.openssl.org/docs/

0
看了该问题的人还看了