【问题标题】:Encryption of an public rsa key file with Poco fails with "file access error"使用 Poco 加密公共 rsa 密钥文件失败并出现“文件访问错误”
【发布时间】:2018-08-29 08:43:24
【问题描述】:

我正在尝试加密我使用 libary poco crypto 生成的 rsa 公钥。这个想法来自这些答案(C++ Encrypt a text file, allow use of decrypt via ifstream)。公钥的形式为 “MIIBIDANBgkqhkiG…………== 我使用的是使用 OpenSSL 1.0.2g 构建的 ubuntu 16.04 和 poco 库版本 1.7.8p2。

我使用的代码如下:

#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;
        }   
}

当我运行上面的代码时,我得到了异常“文件访问错误” txt 文件被授予读写和执行的所有权限。 之后我尝试使用 RSAKey 类提供的 istream 构造函数:

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;

    }

}

但我遇到了同样的错误。

当我用以下行替换上面的代码时它起作用了:

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

但这不是我想要的。 我还使用

将文本文件打印成字符串
ifstream myfile("pubkey.txt");
string file;
myfile >> file;
file;

并且文件被正确写入字符串。

在这种情况下我做错了什么?

【问题讨论】:

  • 为什么要加密 public 密钥?公钥是,错误的,public
  • @Martin Bonner 我假设公钥将用于加密数据,因为密钥对在数学上是相关的,用公钥加密的任何内容都只能由其对应的私钥解密,反之亦然.但重点是代码不能正常工作
  • 啊!抱歉,您说“我正在尝试加密 rsa 公钥” - 这意味着密钥的值是您尝试从中生成密文的明文(可能使用另一个密钥)。这并不完全是疯狂的,因为非对称密钥通常只用于加密其他密钥(通常是对称密钥,然后用于加密实际消息)。我认为您的意思是“我正在尝试使用 rsa 公钥加密 ” - 这意味着您有一些明文并希望使用该密钥将其转换为密文。

标签: c++ text public-key-encryption poco-libraries


【解决方案1】:

我也遇到过同样的问题,原来是格式错误。

我的一个朋友看到文件格式错误并修复它并且它工作。

确保文件格式正确,检查每一行结尾。

这是来自 VIM 的文件截图。此外,文件扩展名是.pub.pem。我不确定文件扩展名是否会影响它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2014-12-03
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多