我正在编写客户端/服务器加密程序并想发送 ECIES 公钥。为此,我必须将公钥序列化到文件,将文件读取到字节数组,发送这个字节数组。另一方面:接收字节数组,将其写入文件,从文件中反序列化公钥。因此,我编写了一些测试项目,尝试将其与出色的系统分开进行,并且(当所有这些模块都成功运行时)只需将其插入我的项目中。这个项目的代码是:
class EncoderRSA
{
public:
EncoderRSA();
void keyGeneration();
std::string encrypt(std::string plainText);
std::string decrypt(std::string cypher);
void setRsaPublicKey(char *publicKeyInCharArray);
char *getRsaPublicKey();
private:
AutoSeededRandomPool prng; // Pseudo Random Number Generator
ECIES<ECP>::Decryptor rsaDecryptor;
ECIES<ECP>::Encryptor rsaEncryptor;
};
而且,严格来说,主要(用于问题)方法:
char *EncoderRSA::getRsaPublicKey() {
std::string file = "publicKey.txt";
//Save public key in file
FileSink sink(file.c_str());
this->rsaEncryptor.GetPublicKey().Save(sink);
//Read file with public key into the buffer
std::ifstream infile (file.c_str(),std::ifstream::binary);
if (!infile.is_open()) {
std::cout << "Can't open file to write" << std::endl;
exit(1);
}
// get size of file
infile.seekg (0,infile.end);
long size = infile.tellg();
infile.seekg (0);
// allocate memory for file content
char* buffer = new char[size];
infile.read (buffer,size);
infile.close();
return buffer;
}
void EncoderRSA::setRsaPublicKey(char *publicKeyInCharArray) {
std::string file = "publicKey.txt";
int size = strlen(publicKeyInCharArray);
//Write received public key in file
std::ofstream outfile (file.c_str(),std::ofstream::binary);
if (!outfile.is_open()) {
std::cout << "Can't open file to write" << std::endl;
exit(1);
}
outfile.write (publicKeyInCharArray,size);
outfile.close();
// release dynamically-allocated memory
delete[] publicKeyInCharArray;
//Load public key from file
FileSource source(file.c_str(), true);
this->rsaEncryptor.AccessPublicKey().Load(source);
}
代码main.cpp
:
int main() {
char *buffer = keysEncoder.getRsaPublicKey();
cout << "buffer: " << buffer << endl;
//...
//send buffer
//receive buffer from other side
//..
keysEncoder.setRsaPublicKey(buffer);
string decoded = keysEncoder.decrypt(cypher);
cout << "decoded: " << decoded << endl;
return 0;
}
但它因错误而崩溃:
terminate called after throwing an instance of 'CryptoPP::BERDecoderErr'
wait(): BER decode error
Aborted (core dumped)
Process returned 134 (0x86) execution time: 2.891
为什么?