C++最新使用开源openssl实现输入是文件,输出是文件的AES加解密的代码
生活随笔
收集整理的這篇文章主要介紹了
C++最新使用开源openssl实现输入是文件,输出是文件的AES加解密的代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
AES.h頭文件
#include <cstring> #include <fstream> #include <iostream> #include <openssl/aes.h>//AES文件加密函數 int aes_encrypt_file(const std::string &original_backup_file_path,const std::string &encrypted_file_path,const std::string &password) {//創建 ass_key 對象AES_KEY aes_key{};AES_set_encrypt_key(reinterpret_cast<const uint8_t*>(password.c_str()), 256, &aes_key);//定義加密塊的大小,必須是16字節int encrypt_chunk_size = 16;std::ifstream original_backup_file(original_backup_file_path,std::ios::binary);std::ofstream encrypted_file(encrypted_file_path, std::ios::binary);char aes_encrypt_in[encrypt_chunk_size + 1];char aes_encrypt_out[encrypt_chunk_size +1];while (!original_backup_file.eof()) {original_backup_file.read(aes_encrypt_in, encrypt_chunk_size);if (original_backup_file.gcount() < encrypt_chunk_size) {encrypted_file.write(aes_encrypt_in, original_backup_file.gcount());} else {AES_encrypt(reinterpret_cast<const unsigned char*>(aes_encrypt_in),reinterpret_cast<unsigned char*>(aes_encrypt_out),&aes_key);encrypted_file.write(aes_encrypt_out, original_backup_file.gcount());}};encrypted_file.close();original_backup_file.close();return 0; }//AES文件解密函數 int aes_decrypt_file(const std::string &encrypted_file_path,const std::string &decrypted_file_path,const std::string &password) {AES_KEY aes_key{};AES_set_decrypt_key(reinterpret_cast<const uint8_t*>(password.c_str()), 256, &aes_key);int encrypt_chunk_size = 16;std::ifstream encrypted_file(encrypted_file_path, std::ios::binary);std::ofstream decrypted_file(decrypted_file_path, std::ios::binary);char aes_decrypt_in[encrypt_chunk_size + 1];char aes_decrypt_out[encrypt_chunk_size +1];while (!encrypted_file.eof()) {encrypted_file.read(aes_decrypt_in, encrypt_chunk_size);if (encrypted_file.gcount() < encrypt_chunk_size) {decrypted_file.write(aes_decrypt_in, encrypted_file.gcount());} else {AES_decrypt(reinterpret_cast<const unsigned char*>(aes_decrypt_in),reinterpret_cast<unsigned char*>(aes_decrypt_out),&aes_key);decrypted_file.write(aes_decrypt_out, encrypted_file.gcount());}};encrypted_file.close();decrypted_file.close();return 0; }main函數調用
#include "AES.h"int main(){//Test AES.h encstd::string enc_from = "/home/gsc/Projects/1.txt";std::string enc_to_dec_from = "/home/gsc/Projects/2.enc";std::string dec_to ="/home/gsc/Projects/3.txt";std::string password = "Cxt123456";aes_encrypt_file(enc_from,enc_to_dec_from,password);//Test AES.h decaes_decrypt_file(enc_to_dec_from,dec_to,password); }?
總結
以上是生活随笔為你收集整理的C++最新使用开源openssl实现输入是文件,输出是文件的AES加解密的代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡逾期还款记录会影响贷款吗?这种情况
- 下一篇: ubuntu修改字体 样式