在 Linux 下用 C++ 做“加密”,先明确你要做什么,因为不同场景用的技术完全不同。下面我按常见需求给你一个清晰、实用的指引,并附示例代码。
| 需求 | 推荐方案 |
|---|---|
| 保存密码(不可逆) | 哈希 + 盐(SHA-256 / bcrypt / Argon2) |
| 文件 / 数据加密(可逆) | AES(对称加密) |
| 网络通信安全 | TLS / SSL(OpenSSL) |
| 密钥交换 / 签名 | RSA / ECC(非对称加密) |
| 简单混淆(不是真加密) | Base64、XOR(不安全) |
Linux 几乎都有,C++ 可直接用。
sudo apt install libssl-dev
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <cstring>
#include <iostream>
void handleErrors() {
ERR_print_errors_fp(stderr);
abort();
}
int encrypt(
unsigned char *plaintext,
int plaintext_len,
unsigned char *key,
unsigned char *iv,
unsigned char *ciphertext
) {
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) handleErrors();
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, iv))
handleErrors();
int len, ciphertext_len;
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
handleErrors();
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int main() {
unsigned char key[32]; // 256-bit
unsigned char iv[16]; // 128-bit
RAND_bytes(key, sizeof(key));
RAND_bytes(iv, sizeof(iv));
unsigned char plaintext[] = "Hello Linux C++ Encryption";
unsigned char ciphertext[128];
int len = encrypt(plaintext, strlen((char*)plaintext), key, iv, ciphertext);
std::cout << "Encrypted length: " << len << std::endl;
return 0;
}
编译:
g++ aes_example.cpp -o aes_example -lssl -lcrypto
#include <openssl/sha.h>
#include <iostream>
int main() {
const char *password = "mypassword";
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256((unsigned char*)password, strlen(password), hash);
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
printf("%02x", hash[i]);
putchar('\n');
}
⚠️ 真实项目中一定要加盐!
适合:
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem
C++ 使用 OpenSSL API 较复杂,一般:
sudo apt install libsodium-dev
#include <sodium.h>
#include <cstdio>
int main() {
sodium_init();
unsigned char key[crypto_secretbox_KEYBYTES];
unsigned char nonce[crypto_secretbox_NONCEBYTES];
unsigned char plaintext[] = "Secret";
unsigned char ciphertext[sizeof(plaintext) + crypto_secretbox_MACBYTES];
randombytes_buf(key, sizeof(key));
randombytes_buf(nonce, sizeof(nonce));
crypto_secretbox_easy(
ciphertext,
plaintext,
sizeof(plaintext),
nonce,
key
);
printf("Encrypted successfully\n");
}
编译:
g++ sodium_example.cpp -lsodium
✅ libsodium 几乎是 Linux C++ 加密首选
❌ 不要自己实现加密算法
❌ 不要用 rand() 生成密钥
❌ 不要硬编码密钥
✅ 使用成熟库(OpenSSL / libsodium)
✅ 对称加密一定要随机 IV / nonce
你可以直接告诉我:
我可以直接给你完整可用的工程级代码。