给定一个字符串“TEST”,我想将它转换为一个字符数组
char goal[] = "TEST";
这是我将字符串复制到 char* 的方法:
char *test=new char[k.size()+1];
test[k.size()]=0;
memcpy(test,k.c_str(),k.size());
上面的方法确实有效,或者似乎有效。
假设我只有:
char goal[] = "TEST";
然后我使用 GDB 调试我的代码,如下所示:
(gdb) b function
(gdb) p goal
$1 = "TEST"
但是,当我使用上面的代码将字符串复制到 char* 时,调试器输出:
(gdb) b function
(gdb) p test
$2 = 0x1001000d0 "TEST"
在打印时,没有变化。他们都打印“TEST”(使用 cout 或其他)。但是,这改变了我的代码中的所有内容:
#include <openssl/engine.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
function(string A, string B)
{
// The following two lines yield to correct solution: AFF791FA574D564C83F6456CC198CBD316949DC9
char key[] = "Password";
char data[] = "Message";
/* Alternative yields to: 2b2c26033b2dcfc22051941c31bd3cf54f96816d
string k = "Password";
char *key=new char[k.size()+1];
key[k.size()]=0;
memcpy(key,k.c_str(),k.size());
char *data=new char[d.size()+1];
data[d.size()]=0;
memcpy(data,d.c_str(),d.size());
*/
unsigned char* result;
unsigned int len = 20;
result = (unsigned char*)malloc(sizeof(char) * len);
HMAC_CTX ctx;
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
HMAC_CTX_init(&ctx);
// Using sha1 hash engine here.
// You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etc
HMAC_Init_ex(&ctx, key, strlen(key), EVP_sha1(), NULL);
HMAC_Update(&ctx, (unsigned char*)&data, strlen(data));
HMAC_Final(&ctx, result, &len);
HMAC_CTX_cleanup(&ctx);
// cout << key << " - " << data << endl;
cout << "HMAC digest: " << endl;
for (unsigned int i = 0; i != len; i++)
printf("%02x", (unsigned int)result[i]);
}