carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

user03:字符串Hex格式Key转换为数组(hex-key-to-array) #172

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

用户使用Key和IV是HEX字符串的形式:

#define KEY "60EaE9193555278880261c1995531f87B5097E494684F0CE1DBB50ABF625A82f"  // strlen is 64
#define IV  "631179b14B3D7D2E1E2D484360EAe919" // strlen is 32

请转化成数组,例如上述Key转化为uint8_t array[] = {0x60, 0xea, 0xe9 ....},注意Key和IV中可能同时存在大写和小写字母,请正确处理它们。

carloscn commented 1 year ago

问题分析

int32_t utils_convert_char_to_nibble(uint8_t inchar, uint8_t *num)
{
    int32_t ret = 0;

    UTILS_CHECK_PTR(num);

    /* Convert the char to nibble */
    if ((inchar >= (uint8_t)'0') && (inchar <= (uint8_t)'9')) {
        *num = inchar - (uint8_t)'0';
    } else if ((inchar >= (uint8_t)'a') && (inchar <= (uint8_t)'f')) {
        *num = inchar - (uint8_t)'a' + 10U;
    } else if ((inchar >= (uint8_t)'A') && (inchar <= (uint8_t)'F')) {
        *num = inchar - (uint8_t)'A' + 10U;
    } else {
        ret = -1;
    }

finish:
    return ret;
}

int32_t utils_convert_str_to_be(const char *str, uint8_t *buf, size_t len)
{
    int32_t ret = -1;
    size_t c_len = 0;
    uint8_t lower_nibble, upper_nibble;

    UTILS_CHECK_PTR(str);
    UTILS_CHECK_PTR(buf);

    /* Len has to be multiple of 2 */
    if ((0 == len) || (len % 2 == 1)) {
        goto finish;
    }

    c_len = 0;
    while (c_len < len) {
        if (utils_convert_char_to_nibble(str[c_len], &upper_nibble) == 0) {
            if (utils_convert_char_to_nibble(str[c_len + 1], &lower_nibble) == 0) {
                buf[c_len / 2] = (upper_nibble << 4) | lower_nibble;
            } else {
                goto finish;
            }
        } else {
            goto finish;
        }
        c_len += 2;
    }
    ret = 0;

finish:
    return ret;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/551991 https://github.com/carloscn/structstudy/blob/master/c_programming/utils/utils.c#L894