如何将char数组转换为字符串

时间:2018-05-17 00:01:19

标签: c++

char n[12];
sgx_read_rand(reinterpret_cast<unsigned char*>(&n),
                sizeof(n));
mbedtls_printf("ENCLAVE: Salt for the password: %llu\n", *(char *)n);
string salt(n);
mbedtls_printf("ENCLAVE: Salt for the password: %s\n", salt.c_str());

它输出为:

ENCLAVE:Salt代码:4294967209

ENCLAVE:密码为Salt: Æ Ѩ

如何将其转换为字符串?它甚至可能吗?

功能签名:

/* sgx_read_rand()
 * Parameters:
 *      rand - the buffer to receive the random number
 *      length_in_bytes - the number of bytes to read the random number
 * Return Value:
 *      SGX_SUCCESS - success
 *      SGX_ERROR_INVALID_PARAMETER - the parameter is invalid
 *      SGX_ERROR_UNEXPECTED - HW failure of RDRAND instruction
*/
sgx_status_t SGXAPI sgx_read_rand(unsigned char *rand, size_t length_in_bytes);

我想要的是什么:

我希望salt作为字符串数据类型获取。我的密码是一个字符串数据类型,我想与它连接盐。正如你所看到的,当我尝试从char数组中获取字符串时,我得到了二进制数据,但是当我使用%llu作为char数组时,我得到了可读数据。我希望字符串中的可读数据相同。

从Linux SGX开发者文档更新: sgx_read_rand

The sgx_read_rand function is used to generate a random number inside
the enclave.
Syntax
sgx_status_t sgx_read_rand(
unsigned char *rand,
size_t length_in_bytes
);

rand variable:
A pointer to the buffer that receives the random number. The pointer cannot be NULL. The rand buffer can be either within or outside the enclave, but it is not allowed to be across the enclave boundary or wrapped around.
length_in_bytes [in]
The length of the buffer (in bytes)

链接到开发人员参考:https://01.org/sites/default/files/documentation/intel_sgx_sdk_developer_reference_for_linux_os_pdf.pdf

所有关注此问题的人,请看这里: https://github.com/intel/linux-sgx/issues/263

所以我根据评论做了这个:

char n[12];
sgx_read_rand(reinterpret_cast<unsigned char*>(&n),
                sizeof(n));

for(int i=0;i<12;++i)
{
    mbedtls_printf("%u\n", (unsigned int)n[i]);
}

输出

15
73
8
4294967229
84
4294967176
53
4294967198
4294967268
91
4294967275
4294967224

我认为这个函数只生成随机字节。有什么意见吗?

1 个答案:

答案 0 :(得分:0)

首先,是的,可以将其转换为字符串。但你必须了解你正在使用的类型。

char n[12];

这里的n是char *类型。如果要将char *转换为字符串,则必须将其终止。因此,在使用随机数填充数组后,您必须:

n[sizeof(n)-1] = '\0';

然后

string salt(n);

包含表示char数组的字符串。但要注意,随机数可能已包含'\ 0',因此结果字符串的长度可能会有所不同。 (0到11个字符)

让我解释一下,代码中发生了什么:

mbedtls_printf("ENCLAVE: Salt for the password: %llu\n", *(char *)n);

这里,因为n已经是char *,所以你取* n,它与n [0]相同,并输出为%llu(unsigned long long int)。十六进制的输出4294967209是0xFFFFFFA9。你得到这个值是因为你将char n [0] = 0xA9 = -87转换为unsigned long long int。

您以后获得的字符串“ Æ Ѩ ”是正确的,即您创建的随机字符。但这是纯粹的运气,你的记忆中有一个'\ 0',它终止了字符串。这看起来像Unicode,我不确定您的环境是什么,但您可能需要转换为wchar_t,具体取决于您的密码存储的格式。但这超出了你的问题的范围。

相关问题