I am writing a client / server program and want to send the ECIES public key. To do this, I have to serialize the public key into a file, read the file into a byte array, send this array of bytes. On the other hand: get an array of bytes, write it to a file, deserialize the public key from the file. So, I wrote several test projects to try to do this separately from an excellent system, and (when this whole module works successfully) just paste it into my project. Code for this project:
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;
ECIES<ECP>::Decryptor rsaDecryptor;
ECIES<ECP>::Encryptor rsaEncryptor;
};
And, strictly speaking, simple (for the task) methods:
char *EncoderRSA::getRsaPublicKey() {
std::string file = "publicKey.txt";
FileSink sink(file.c_str());
this->rsaEncryptor.GetPublicKey().Save(sink);
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);
}
infile.seekg (0,infile.end);
long size = infile.tellg();
infile.seekg (0);
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);
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();
delete[] publicKeyInCharArray;
FileSource source(file.c_str(), true);
this->rsaEncryptor.AccessPublicKey().Load(source);
}
Code main.cpp:
int main() {
char *buffer = keysEncoder.getRsaPublicKey();
cout << "buffer: " << buffer << endl;
keysEncoder.setRsaPublicKey(buffer);
string decoded = keysEncoder.decrypt(cypher);
cout << "decoded: " << decoded << endl;
return 0;
}
But he crashed with an error:
terminate called after throwing an instance of 'CryptoPP::BERDecoderErr'
wait(): BER decode error
Aborted (core dumped)
Process returned 134 (0x86) execution time: 2.891
Why?
source
share