最近工作需要使用到加密,对于程序内的数据就采用了对称加密,于是就使用了AES加密。废话不多说了,直接上代码
bob_aes.h
#ifndef bob_aes_h #define bob_aes_h #include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <cstdlib> #include <openssl/aes.h> class BobAES { public: BobAES(); ~BobAES(); std::string aes_encrypt(std::string msg); std::string aes_decrypt(std::string msg); private: int MSG_LEN; char key[AES_BLOCK_SIZE]; }; #endif
bob_aes.cpp
#include "bob_aes.h" BobAES::BobAES() : MSG_LEN(0) { for(int i = 0; i < AES_BLOCK_SIZE; i++) { key[i] = 32 + i; } } BobAES::~BobAES() { } std::string BobAES::aes_encrypt(std::string msg) { int i = msg.size() / 1024; MSG_LEN = ( i + 1 ) * 1024; //MSG_LEN = msg.size() + 16; char in[MSG_LEN]; char out[MSG_LEN+16]; memset((char*)in,0,MSG_LEN); memset((char*)out,0,MSG_LEN+16); strncpy((char*)in,msg.c_str(),msg.size()); unsigned char iv[AES_BLOCK_SIZE]; //加密的初始化向量 for(int j = 0; j < AES_BLOCK_SIZE; ++j) { iv[j] = 0; } AES_KEY aes; if(AES_set_encrypt_key((unsigned char*)key, 128, &aes) < 0) { return NULL; } int len = msg.size(); AES_cbc_encrypt((unsigned char*)in,(unsigned char*)out,len,&aes,iv,AES_ENCRYPT); std::string encrypt_msg(&out[0],&out[MSG_LEN+16]); for(int i= 0;out[i];i++){ printf("%x",(unsigned char)out[i]); //std::cout << dstStringTemp[i]; } std::cout << std::endl; return encrypt_msg; } std::string BobAES::aes_decrypt(std::string msg) { MSG_LEN = msg.size(); char in[MSG_LEN]; char out[MSG_LEN+16]; memset((char*)in,0,MSG_LEN); memset((char*)out,0,MSG_LEN+16); strncpy((char*)in,msg.c_str(),msg.size()); for(int i= 0;in[i];i++){ printf("%x",(unsigned char)in[i]); //std::cout << dstStringTemp[i]; } std::cout << std::endl; unsigned char iv[AES_BLOCK_SIZE]; //加密的初始化向量 for(int j = 0; j < AES_BLOCK_SIZE; ++j) { iv[j] = 0; } AES_KEY aes; if(AES_set_decrypt_key((unsigned char*)key, 128, &aes) < 0) { return NULL; } int len = msg.size(); AES_cbc_encrypt((unsigned char*)in,(unsigned char*)out,len,&aes,iv,AES_DECRYPT); std::string decrypt_msg = out; return decrypt_msg; }
这个代码还存在一些问题,对于字节在96以内的字符串可以加密解密成功,但96及以上字节的字符串加密解密后就会出现乱码,对这方面我还是新手,请大神们多多指正。
时间: 2024-10-13 18:50:05