简体   繁体   中英

Encryption of an public rsa key file with Poco fails with "file access error"

I'm trying to encrypt an rsa public key that I have generated using libary poco crypto. The idea came from these answers ( C++ Encrypt a text file, allow use of decrypt via ifstream ). The pubkey is in the form of "MIIBIDANBgkqhkiG.........== I'm using ubuntu 16.04 and poco library version 1.7.8p2 which has been built with OpenSSL 1.0.2g.

The code I use is the following:

#include <iostream>
#include <fstream> 
#include "Poco/Crypto/CipherFactory.h"
#include "Poco/Crypto/Cipher.h"
#include "Poco/Crypto/RSADigestEngine.h"

using namespace std;
using namespace Poco::Crypto;

int main(int argc, char** argv)   
{ 
    try {
  Cipher::Ptr pCipher = CipherFactory::defaultFactory().createCipher(RSAKey("pubkey.txt"));       
    } 
    catch (const exception& exc)
        {
            cout << exc.what() << endl;
        }   
}

When I run the above code I get the exception "file access error" The txt file is given all the permissions to read write and execute. Afterwards I tried with the istream constructor that RSAKey class provides:

int main(int argc, char** argv)

{
    try {

        ifstream myfile("pubkey.txt");
        Cipher::Ptr pCipher = CipherFactory::defaultFactory().createCipher(RSAKey(&myfile));

    catch (const exception& exc)

    {

      cout << exc.what() << endl;

    }

}

But I got the same error.

It worked when I replaced the above code with the following line:

Cipher::Ptr pCipher = CipherFactory::defaultFactory().createCipher(RSAKey(RSAKey::KL_1024, RSAKey::EXP_SMALL));

But this is not what I want. I also print the text file into a string by using

ifstream myfile("pubkey.txt");
string file;
myfile >> file;
file;

and the file is correctly written into the string.

What am I doing wrong in this case?

I have faced the same problem and it turned out to be format error.

A friend of mine saw that the file format was wrong and fixed it and it worked.

Make sure that the file format is right, check every line ending.

Here is a screenshot from VIM for the file. Also, the file extension is .pub or .pem . I'm not sure though if the file extension affect it.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM