首页 > 解决方案 > 在 C 中将 20 字节十六进制(字符字符串)转换为 10 字节二进制字符字符串

问题描述

我存储了以下字符串。1-F 为 16 个字节,最后为 4 个 nullBytes。

e.g. 1234567890ABCDEF0000
unsigned char input[] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x00, 0x00, 0x00, 0x00};

我如何获得这个 10 字节的二进制文件?

编辑:

我试图正确使用 openssl 加密库的 SHA1 函数。我的任务是从命令行读取“盐”和“密码”。

然后将它们加在一起,这样我就有了“盐”+“|” +“密码”。

如果没有传递盐,则盐只是“\0\0\0\0\0\0\0\0\0\0”,即 10 个字节,对吗?但如果通过了盐,它可能是“1234567890ABCDEF”

然后我必须用空字节填充它,这样我总共有 10 个字节但是“1234567890ABCDEF”已经是 16 个字节,所以我必须转换它。我不知道,我真的在 c 中的内存部分苦苦挣扎

标签: chashbinaryhexsha1

解决方案


嘿,我没有从你的例子中得到太多,但你描述为波纹管+约束可以像这样解决。见片段。

如果没有传递盐,则盐只是“\0\0\0\0\0\0\0\0\0\0”,即 10 个字节,对吗?但如果通过了盐,它可能是“1234567890ABCDEF”

#include <stdio.h>
#include <string.h>

#define SALT_MAX_BYTES 10

int main(int argc, char *argv[]) {
    // Init the whole array with 0-s, which is the same value as '\0'
    char salt[SALT_MAX_BYTES] = {0};
    // Here get the input, now assuming ./a.out [salt]
    if (argc > 1) // The executable name is always passed
    {
        printf("Input: %s\n", argv[1]);
        // Assuming ASCII...
        // Assuming you want to use the ASCII value representation of input "42"
        // and not the number 42 ... 
        strncpy(salt, argv[1], SALT_MAX_BYTES);
        // Note: from here on you must strictly handle salt as length terminated.
        // => input may have more then SALT_MAX_BYTES
    }
    else
    {
        puts("Usage: ...");
        return -1;
    }

    // Left aligned output, showing nothing for \0 bytes...
    printf("Entered salt is : <%-*.*s>\n", SALT_MAX_BYTES, SALT_MAX_BYTES, salt);
    return 0;
}

推荐阅读