将格式化打印值存储在新变量中

时间:2015-12-21 16:31:53

标签: c sha256

在加密函数(sha256)中,我有这段代码用于打印最终结果:

<?php

echo "<h1>" . $_POST["beschreibung"] . "</h1>";
echo "<h1>" . $_POST["bild"] . "</h1>";

?>

<script>
    function dialResponse() {
        console.log(this.responseText); //should be return value of 1
    }

    var oReq = new XMLHttpRequest();
    oReq.onload = dialResponse;
    oReq.open("get", "https://{account}.cartodb.com/api/v2/sql?q=INSERT INTO cartodb_test (caption, image_low, image_standard, image_thumb, latitude, longitude) VALUES (<?php echo $beschreibung;?>, http://app.seedbomb.city/images/<?php echo $bild;?>, http://app.seedbomb.city/images/<?php echo $bild;?>, http://app.seedbomb.city/images/<?php echo $bild;?>, 12.532534, 12.643245)&api_key=http://app.seedbomb.city/images/<?php echo $bild;?>"
            ", true);
            oReq.send();
</script>

当哈希在函数中输入时类似于:

void print_hash(unsigned char hash[]) 
   {
       int idx;
       for (idx=0; idx < 32; idx++)
          printf("%02x",hash[idx]);
       printf("\n");
    }

然后,通过循环,我在控制台中进入

/A�`�}#.�O0�T����@�}N�?�#=\&@

我想知道如何在变量控制台中存储最终值。 我对sscanf有所了解,但你可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

您可以使用sprintf

将其存储在数组中(通过指针传递参数)
void print_hash(unsigned char hash[], unsigned char output[])
{
    int idx;
    for (idx = 0; idx < 32; idx++)
        sprintf(&output[2 * idx], "%02x", hash[idx]);
}

请务必在output(即char output[2 * 32 + 1])中为空终止符保留一个额外字节。

答案 1 :(得分:0)

使用sprintf,此函数将其输出(相当于printf写入控制台的内容)存储在字符串缓冲区中。在您的案例中如何使用它的示例:

char buffer[65]; //Make this buffer large enough for the string and a nul terminator
for(int idx = 0; idx < 32; ++idx)
{
    sprintf(&buffer[2*idx], "%02x", hash[idx]); //Write to the correct position in the buffer
}

终止空字符由sprintf自动附加。

答案 2 :(得分:0)

您还可以避免使用sprintf()并制作更有效的功能

void
hash2digest(char *result, const char *const hash, size_t length)
{
    const char *characters = "0123456789abcdef";
    for (size_t i = 0 ; i < length ; ++i)
    {
        result[2 * i] = characters[(hash[i] >> 0x04) & 0x0F];
        result[2 * i + 1] = characters[hash[i] & 0x0F];
    }
    result[2 * length] = '\0';    
}

请注意,你可以在任何你想要的地方调用它(假设hash已经被声明和定义)

char digest[65];
hash2digest(digest, hash, 32);

这反过来可以重用SHA1,例如,像这样

char digest[41];
hash2digest(digest, hash, 20);

并使用动态内存分配

char *
hash2digest(const char *const hash, size_t length)
{
    const char *characters = "0123456789abcdef";
    char *result;
    result = malloc(2 * length + 1);
    if (result == NULL)
        return NULL;
    for (size_t i = 0 ; i < length ; ++i)
    {
        result[2 * i] = characters[(hash[i] >> 0x04) & 0x0F];
        result[2 * i + 1] = characters[hash[i] & 0x0F];
    }
    result[2 * length] = '\0';

    return result;
}