【问题标题】:Inputting a file address from a .text file to OpenSSL encryption function in C++?将 .text 文件中的文件地址输入到 C++ 中的 OpenSSL 加密函数?
【发布时间】:2021-04-03 19:11:45
【问题描述】:

我想将 .txt 文件中的多行输出定向到该 encrypt() 函数。 .txt 文件包含我要加密的文件的地址。代码可以编译,但没有加密。我正在使用 EVP_aes_256_cbc() 进行加密。我做错了什么?

int encrypt(unsigned char* plaintext, int plaintext_len, unsigned char* key, unsigned char* iv, unsigned char* ciphertext);
int decrypt(unsigned char* ciphertext, int ciphertext_len, unsigned char* key, unsigned char* iv, unsigned char* plaintext);


int main() {
    unsigned char key[16];
    RAND_bytes(key, sizeof(key));

    unsigned char iv[16];
    RAND_bytes(iv, sizeof(iv));

    std::ifstream file("C:\\Users\NULL\source\repos\xFolder\YFolder\\test.txt");
    std::string str;
    while (std::getline(file, str))
    {
        int encrypt(unsigned char* str, int plaintext_len, unsigned char* key,unsigned char* iv, unsigned char* ciphertext);
    } 

【问题讨论】:

  • 除了 Mike 的回答中指出的错误之外,encryptdecrypt 看起来是错误的。固定:int encrypt(const unsigned char* plaintext, int plaintext_len, const unsigned char* key, const unsigned char* iv, unsigned char* ciphertext);int decrypt(const unsigned char* ciphertext, int ciphertext_len, const unsigned char* key, const unsigned char* iv, unsigned char* plaintext);
  • @Ted 感谢您的输入,但根据您的建议,我的代码无法编译,错误 LNK2001 unresolved external symbol "int __cdecl encrypt(unsigned char const *,int,unsigned char const *,unsigned char const *,unsigned char *)" (?encrypt@@YAHPEBEH00PEAE@Z)
  • 这些函数不是你自己定义的或者是从 OpenSSL 主页的 C 示例中复制过来的吗?
  • Ted 我没有从 OpenSSL 页面复制。谢谢,你帮了大忙。
  • 不客气!函数签名看起来与OpenSSL wiki 中的示例非常相似,并且可能存在相同的问题(不正确的const 应该在哪里)所以我想你可以同时更改声明和定义(除非它们被定义在某个地方你不能改变它)。

标签: c++ encryption openssl aes


【解决方案1】:

在 C++ 中,\ 用于转义序列,因此您必须编写 \\ 以在字符串文字中表达 \

您实际上是为第一个和最后一个 \ 执行此操作,但您必须为其他 \s 执行此操作。

    std::ifstream file("C:\\Users\NULL\source\repos\xFolder\YFolder\\test.txt");

应该是

    std::ifstream file("C:\\Users\\NULL\\source\\repos\\xFolder\\YFolder\\test.txt");

也在这个循环中

    while (std::getline(file, str))
    {
        int encrypt(unsigned char* str, int plaintext_len, unsigned char* key,unsigned char* iv, unsigned char* ciphertext);
    } 

您没有调用该函数,而是仅声明了该函数。

您应该调用该函数进行加密。可能是这样的:

    while (std::getline(file, str))
    {
        std::vector<unsigned char> encrypted_str(str.size()); // you may need some more bytes
        encrypt(reinterpret_cast<unsigned char*>(str.data()), str.size(), key, iv, &encrypted_str[0]);
    } 

【讨论】:

  • 替代方案:R"aw(C:\Users\NULL\source\repos\xFolder\YFolder\test.txt)aw""C:/Users/NULL/source/repos/xFolder/YFolder/test.txt"
  • 感谢 Mike 回复 MSVS 2019,在更正您建议的问题后,它给了我这个错误。错误 C2440: 'static_cast': 无法从 '_Elem *' 转换为 'unsigned char *' 1> with 1> [ 1> _Elem=char 1> ]
  • ``` 指向的类型不相关;转换需要 reinterpret_cast、C-style cast 或 function-style cast ```
猜你喜欢
  • 2018-11-28
  • 2020-04-14
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2011-11-25
  • 1970-01-01
  • 2019-03-31
相关资源
最近更新 更多