在 Linux 上使用 C++ 進行工業智能加密,需要遵循以下步驟:
安裝必要的開發工具和庫:
首先,確保已經安裝了以下工具:
可以使用以下命令安裝這些工具:
sudo apt-get update
sudo apt-get install build-essential cmake libboost-all-dev libssl-dev
創建一個新的 C++ 項目:
使用 CMake 創建一個新的 C++ 項目。首先,創建一個名為 CMakeLists.txt
的文件,其中包含以下內容:
cmake_minimum_required(VERSION 3.10)
project(Industrial_Intelligence_Encryption)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# 添加 Boost 庫
find_package(Boost REQUIRED COMPONENTS system)
# 添加 OpenSSL 庫
find_package(OpenSSL REQUIRED)
include_directories(${Boost_INCLUDE_DIRS} ${OpenSSL_INCLUDE_DIRS})
add_executable(industrial_intelligence_encryption main.cpp)
# 鏈接庫
target_link_libraries(industrial_intelligence_encryption ${Boost_LIBRARIES} ${OpenSSL_LIBRARIES})
編寫 C++ 代碼:
在項目中創建一個名為 main.cpp
的文件,并編寫以下 C++ 代碼:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <openssl/aes.h>
#include <openssl/err.h>
using namespace boost::asio;
using namespace std;
const int AES_BLOCK_SIZE = 16;
void encrypt(const unsigned char *plaintext, unsigned char *ciphertext, const unsigned char *key) {
AES_KEY enc_key;
AES_set_encrypt_key(key, AES_BLOCK_SIZE * 8, &enc_key);
AES_cbc_encrypt(plaintext, ciphertext, AES_BLOCK_SIZE, &enc_key, nullptr, AES_ENCRYPT);
}
void decrypt(const unsigned char *ciphertext, unsigned char *plaintext, const unsigned char *key) {
AES_KEY dec_key;
AES_set_decrypt_key(key, AES_BLOCK_SIZE * 8, &dec_key);
AES_cbc_encrypt(ciphertext, plaintext, AES_BLOCK_SIZE, &dec_key, nullptr, AES_DECRYPT);
}
int main() {
try {
io_context io;
// 生成隨機密鑰
unsigned char key[AES_BLOCK_SIZE] = {0};
RAND_bytes(key, AES_BLOCK_SIZE);
// 生成隨機初始化向量
unsigned char iv[AES_BLOCK_SIZE] = {0};
RAND_bytes(iv, AES_BLOCK_SIZE);
// 待加密的明文
string plaintext("Hello, Industrial Intelligence Encryption!");
unsigned char *ciphertext = new unsigned char[plaintext.size() + AES_BLOCK_SIZE];
// 加密
encrypt((unsigned char *)plaintext.c_str(), ciphertext, key);
// 解密
unsigned char *decrypted_text = new unsigned char[plaintext.size()];
decrypt(ciphertext, decrypted_text, key);
// 輸出結果
cout << "Plaintext: " << plaintext << endl;
cout << "Ciphertext: ";
for (int i = 0; i < plaintext.size(); ++i) {
cout << hex << (int)ciphertext[i];
}
cout << endl;
cout << "Decrypted text: " << string(reinterpret_cast<char *>(decrypted_text), plaintext.size()) << endl;
delete[] ciphertext;
delete[] decrypted_text;
} catch (exception &e) {
cerr << "Error: " << e.what() << endl;
return 1;
}
return 0;
}
編譯和運行項目:
在項目目錄中創建一個名為 build
的文件夾,然后進入該文件夾并運行以下命令以使用 CMake 生成構建文件:
cd build
cmake ..
接下來,使用以下命令編譯項目:
make
最后,使用以下命令運行編譯后的可執行文件:
./industrial_intelligence_encryption
運行程序后,將看到加密和解密后的文本輸出。請注意,這個示例僅用于演示目的,實際應用中可能需要根據具體需求進行調整。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。