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

肉山梅塔
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:密码盐:4294967209

ENCLAVE:密码的盐: Æ Ѩ

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

函数签名:

/* 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

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

味觉

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

char n[12];

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

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

然后

string salt(n);

包含一个代表您的字符数组的字符串。但请注意,随机数可能已经包含一个 '\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,具体取决于您的密码存储的格式。但这超出了您的问题范围。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章