mcrypt_generic处的 C++ mcrypt 错误

c++ mcrypt error at mcrypt_generic

本文关键字:mcrypt 错误 C++ generic 处的      更新时间:2023-10-16

我有以下代码:

[测试.cpp]

#include <mcrypt.h>
#include <string>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
  char algo[] = "rijndael-256";
  char mode[] = "cbc";
   char *block_buffer=(char*)"HELLO!! MY NAME IS: ";
cout<<"here"<<endl;
string s;
char key="1234-5678-9654-7512-7895-2543-12";

  char iv[]  = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};;
  MCRYPT td = mcrypt_module_open(algo, NULL, mode, NULL);
  if (td == MCRYPT_FAILED) { cout<<"error"<<endl;}
int keysize=32;
  int r =  mcrypt_generic_init(td, key, keysize, iv);
if (r<0)
{
    cout<<"error2"<<endl;
    mcrypt_perror(r);
            return 1;
}
 //while ( fread (&block_buffer, 1, 1, stdin) == 1 ) {
   int j=          mcrypt_generic (td, &block_buffer, sizeof(block_buffer));
if (j!=0){std::cout<<"error encrypting"<<std::endl;} // I HAVE ERROR HERE J==0

 //how to print the encrypted string??
 cout<<"buffer "<<block_buffer<<endl; //this is not the encriperd string. why?
    mcrypt_generic_deinit(td);
  mcrypt_module_close(td);
}

我正在测试代码:

$: g++ test.cpp -o tst -lmcrypt  
                      $: ./tst

我在哪里添加

PKCS 7?

我有以下方法:

std::string add_pkcs7_padding(std::string s, std::size_t n)
{
  const std::size_t fill = n - (s.length() % n);
  s.append(fill, static_cast<char>(fill));
  return s;
}
std::string strip_pkcs7_padding(std::string s, std::size_t n)
{
  const std::size_t pad = static_cast<unsigned char>(*s.rbegin());
  return s.substr(0, s.length() - pad);
}

我不知道什么时候应该运行它以及在我的代码中的位置。

需要一些帮助。非常感谢!!

编辑:

我在以下位置有错误: mcrypt_generic (td, &block_buffer, sizeof(block_buffer((;编译器打印值 j=0;

你应该

char*调用mcrypt_generic(),而不是像你那样用char**来调用:

mcrypt_generic(td, block_buffer, sizeof(block_buffer));
                   ^^^           ^^^^^^^^^^^^^^^^^^^^
                                      ouch!

此外,长度是错误的,因为sizeof(block_buffer)只是指针的大小,而不是字符串的大小;如果需要strlen(block_buffer)

但这通常仍然是错误的,因为您需要消息是块大小的倍数。使用填充功能:

std::string s = add_pkcs7_padding(block_buffer, mcrypt_enc_get_block_size(td));
std::vector<char> v(s.begin(), s.end());  // this will hold the encrypted data
mcrypt_generic(td, v.data(), v.size());

顺便说一下,你的明文应该像这样声明:

const char * block_buffer = "HELLO!! MY NAME IS: ";
^^^^^                       ^^^^
  constness!                  no explicit cast!

但是为什么这么笨拙,最好只使用字符串:

std::string plaintext = "HELLO!! MY NAME IS: ";


我认为你可能会从一本好的C++书中受益,并稍微熟悉一下语言的基础知识 - 有一个项目可以做是件好事,但你的大多数问题并不真正与加密或mcrypt有关,而只是一般的C++编程。