在C ++中从'const char *'转换为'unsigned char *'?

时间:2015-04-06 22:24:23

标签: c++

我的加密函数声明如下:int encrypt(unsigned char* keydata, int keydata_len, unsigned char *plaintext, int plaintext_len, unsigned char *ciphertext)。这完全有效,现在我根据给定的片段调用它。

const char *password = "password";
len = encrypt(password, (int)strlen(password), (unsigned char*)(content.c_str()), (int)strlen(content.c_str()), ciphertext);

在编译C ++代码时,我得到一个错误:

crest.cc:52:13: error: no matching function for call to 'encrypt'
      len = encrypt(password, (int)strlen(password), (unsigned char*)(content.c_str()), (int)strlen(content.c_str()), ciphertext);
            ^~~~~~~
./aes.h:10:5: note: candidate function not viable: no known conversion from 'const char *' to 'unsigned char *' for 1st argument
int encrypt(unsigned char* keydata, int keydata_len, unsigned char *plaintext, int plaintext_len, unsigned char *ciphertext);

在C ++中进行类型转换以解决此错误的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

此代码存在一些问题,解决这些问题的唯一(正确)方法是确保首先使用正确的数据类型。

因此,使用const char *password = "password"代替unsigned char password[] = "password";(当然,这可能会让您在strlen时遇到麻烦,因为它不像unsigned char) - 使用sizeof(password)-1将在这个实例中起作用,但作为一般解决方案是不明智的,因为password可能不能直接作为数组提供 - 不确定你应该做什么作为&# 34;理想"解决方案,真的。

现在,可以询问是否对函数进行非常量输入实际上是正确的。如果您拥有encrypt的来源,则可能需要将该功能更改为encrypt(const unsigned char* keydata, size_t keydata_len, const unsigned char* plaintext, size_t plaintext_len, unsigned char* ciphertext) - 当然,strlen的{​​{1}}仍无法解决问题,但是我希望原型能够用于这样的功能。

另一种方法是重写unsigned char函数,仅在内部对encrypt进行强制转换,并使用unsigned输入(相关时为char *)。

请注意,如果您知道原始内容不是const(我认为不能保证const的情况,那么它就无法删除常量EXCEPT ,但std::string::c_str()应该有用)