繁体   English   中英

在 C 中将 20 字节十六进制(字符字符串)转换为 10 字节二进制字符字符串

[英]Convert 20 Byte Hex (char string) to 10 Byte Binary Char String in C

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

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 中的内存部分而苦苦挣扎

最简单的可能是:

创建一个 0 初始化的 10 字节数组:

unsigned char salt[10] = { 0 };

然后使用sscanf()逐字节读取十六进制数字:

sscanf(input, "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx",
              &salt[0], &salt[1], &salt[2], &salt[3], &salt[4],
              &salt[5], &salt[6], &salt[7], &salt[8], &salt[9]);

这将根据需要转换尽可能多的字节; 如果只给出 6 个十六进制数字作为盐,则前三个字节被填充,其余的保持为 0。

这应该符合您的预期。

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

如果没有传递盐,盐只是“\\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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM