c++文件加密解密的方法是什么
在C++中进行文件加密和解密通常采用对称加密算法,其中最常用的是AES(Advanced Encryption Standard)算法。以下是一个简单的C++代码示例,演示如何使用AES算法进行文件加密和解密:
#include <iostream>#include <fstream>#include <openssl/aes.h>#include <openssl/rand.h>void encryptFile(const std::string& inputFile, const std::string& outputFile, const std::string& key) {AES_KEY aesKey;AES_set_encrypt_key((unsigned char*)key.c_str(), 128, &aesKey);std::ifstream in(inputFile, std::ios::binary);std::ofstream out(outputFile, std::ios::binary);unsigned char iv[AES_BLOCK_SIZE];RAND_bytes(iv, AES_BLOCK_SIZE);out.write(reinterpret_cast<const char*>(iv), AES_BLOCK_SIZE);unsigned char inBuffer[AES_BLOCK_SIZE];unsigned char outBuffer[AES_BLOCK_SIZE];int numBytesRead = 0;while (in.read(reinterpret_cast<char*>(inBuffer), AES_BLOCK_SIZE)) {AES_cbc_encrypt(inBuffer, outBuffer, AES_BLOCK_SIZE, &aesKey, iv, AES_ENCRYPT);out.write(reinterpret_cast<char*>(outBuffer), AES_BLOCK_SIZE);numBytesRead += AES_BLOCK_SIZE;}in.close();out.close();}void decryptFile(const std::string& inputFile, const std::string& outputFile, const std::string& key) {AES_KEY aesKey;AES_set_decrypt_key((unsigned char*)key.c_str(), 128, &aesKey);std::ifstream in(inputFile, std::ios::binary);std::ofstream out(outputFile, std::ios::binary);unsigned char iv[AES_BLOCK_SIZE];in.read(reinterpret_cast<char*>(iv), AES_BLOCK_SIZE);unsigned char inBuffer[AES_BLOCK_SIZE];unsigned char outBuffer[AES_BLOCK_SIZE];int numBytesRead = 0;while (in.read(reinterpret_cast<char*>(inBuffer), AES_BLOCK_SIZE)) {AES_cbc_encrypt(inBuffer, outBuffer, AES_BLOCK_SIZE, &aesKey, iv, AES_DECRYPT);out.write(reinterpret_cast<char*>(outBuffer), AES_BLOCK_SIZE);numBytesRead += AES_BLOCK_SIZE;}in.close();out.close();}int main() {std::string inputFile = "plaintext.txt";std::string encryptedFile = "encrypted.bin";std::string decryptedFile = "decrypted.txt";std::string key = "mysecretkey";encryptFile(inputFile, encryptedFile, key);decryptFile(encryptedFile, decryptedFile, key);return 0;}
在上面的示例中,encryptFile
函数用于加密文件,decryptFile
函数用于解密文件。需要注意的是,需要安装OpenSSL库,并在编译时链接对应的库文件。此外,文件加密和解密的过程中需要使用相同的密钥。
上一篇:Django会话指的是什么意思
下一篇:c#获取时间的方法有哪些
c++
输入法切换键是哪个键?输入法切
冬月是哪一个月?冬月是什么意思
个人所得税退税金额怎么算出来的
输入法全角和半角有什么区别?输
a4纸尺寸是多少厘米?a4纸的由来
个人所得税扣除标准?个人所得税
输入法哪个好用?输入法介绍
卡拉OK是哪个国家发明的?卡拉OK
mikutools原神网页版入口链接?m
关机特别慢什么原因?电脑和手机