我有以下代码:
test.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在SHOULT中添加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;
发布于 2011-09-09 16:12:35
您应该使用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++书籍,并稍微熟悉一下该语言的基础知识--有一个项目可供处理是件好事,但您遇到的大多数问题实际上与加密或C++无关,而只是与一般的mcrypt编程有关。
https://stackoverflow.com/questions/7358579
复制相似问题