亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

c++文件加密解密的方法是什么

c++
小億
115
2024-03-06 09:56:00
欄目: 編程語言

在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庫,并在編譯時鏈接對應的庫文件。此外,文件加密和解密的過程中需要使用相同的密鑰。

0
德阳市| 栾城县| 田林县| 承德县| 静海县| 德令哈市| 高要市| 辽源市| 双流县| 武乡县| 甘泉县| 江都市| 广河县| 浑源县| 南澳县| 溆浦县| 曲松县| 南木林县| 青田县| 庆云县| 曲靖市| 铜川市| 循化| 和顺县| 琼中| 正镶白旗| 深泽县| 镇坪县| 蓝田县| 宝山区| 岳普湖县| 遂昌县| 剑川县| 乳山市| 故城县| 平山县| 扬中市| 巫山县| 高淳县| 仁寿县| 宁陕县|