在Linux系统中,C++可以使用多种库和方法来进行数据加密。以下是一些常用的加密库和示例:
#include <iostream>
#include <openssl/aes.h>
#include <openssl/rand.h>
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);
std::string ciphertext(plaintext.size() + AES_BLOCK_SIZE, '\0');
AES_encrypt(reinterpret_cast<const unsigned char *>(plaintext.c_str()), reinterpret_cast<unsigned char *>(&ciphertext[0]), &enc_key);
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);
std::string plaintext(ciphertext.size(), '\0');
AES_decrypt(reinterpret_cast<const unsigned char *>(ciphertext.c_str()), reinterpret_cast<unsigned char *>(&plaintext[0]), &dec_key);
return plaintext;
}
int main() {
std::string key = "this is a 32-byte long key!";
std::string plaintext = "Hello, World!";
std::string encrypted = aes_encrypt(plaintext, key);
std::string decrypted = aes_decrypt(encrypted, key);
std::cout << "Original: " << plaintext << std::endl;
std::cout << "Encrypted: ";
for (char c : encrypted) {
std::cout << std::hex << (int)c;
}
std::cout << std::endl;
std::cout << "Decrypted: " << decrypted << std::endl;
return 0;
}
#include <iostream>
#include <string>
#include <cryptopp/sha.h>
#include <cryptopp/hex.h>
std::string sha256_hash(const std::string &input) {
std::string hash;
CryptoPP::SHA256 hash_alg;
CryptoPP::StringSource(input, true,
new CryptoPP::HashFilter(hash_alg,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(hash)
) // HexEncoder
) // HashFilter
); // StringSource
return hash;
}
int main() {
std::string input = "Hello, World!";
std::string hashed = sha256_hash(input);
std::cout << "Input: " << input << std::endl;
std::cout << "SHA-256: " << hashed << std::endl;
return 0;
}
要编译这些示例,你需要安装相应的库。对于OpenSSL,可以使用以下命令安装:
sudo apt-get install libssl-dev
对于Crypto++,可以使用以下命令安装:
sudo apt-get install libcrypto++-dev
然后使用g++编译示例代码,例如:
g++ aes_example.cpp -o aes_example -lcrypto
g++ sha256_example.cpp -o sha256_example -lcryptopp
请注意,这些示例仅用于演示目的,实际应用中可能需要更复杂的处理,例如密钥派生、填充和初始化向量等。在使用加密库时,请确保遵循最佳实践,以确保数据安全。