enhance hex_decode
This commit is contained in:
parent
0318221f3f
commit
e622107f07
@ -2,6 +2,9 @@
|
||||
|
||||
Cryptographic tools
|
||||
|
||||
Any functions that return string representations of bytes in hexadecimal format will
|
||||
always be formatted with no leading `0x` and lower case letters
|
||||
|
||||
## Functions
|
||||
|
||||
### b64_encode
|
||||
@ -26,22 +29,25 @@ unsigned char *b64_decode(const char *s, size_t sz, size_t *decode_sz);
|
||||
### hex_encode
|
||||
|
||||
Encodes an array of bytes into a string in hex representation. For example, converts
|
||||
`[0xDE, 0xAD, 0xBE, 0xEF]` into `"DEADBEEF"`. The returned string will always be in capital
|
||||
letters with no leading `0x`. User is responsible for the freeing of the returned string
|
||||
`[0xDE, 0xAD, 0xBE, 0xEF]` into `"deadbeef"`. User is responsible for freeing the returned string
|
||||
|
||||
```c
|
||||
const char *hex_encode(const unsigned char *hex, size_t sz);
|
||||
|
||||
// Example
|
||||
unsigned char h[4] = {
|
||||
0xde, 0xad, 0xbe, 0xef
|
||||
};
|
||||
const char *s = hex_encode(h, 4);
|
||||
assert(strcmp(s, "DEADBEEF") == 0);
|
||||
assert(strcmp(s, "deadbeef") == 0);
|
||||
free(s);
|
||||
```
|
||||
|
||||
### hex_decode
|
||||
|
||||
Decodes a string of characters representing hexadecimal bytes into an array of `unsigned char`.
|
||||
For example, converts `"DEADBEEF"` into `[0xDE, 0xAD, 0xBE, 0xEF]`. User is reponsible for the
|
||||
Characters can be in upper or lower case, and can start with a leading `0x` or not.
|
||||
For example, converts `"DEADBEEF"` into `[0xde, 0xad, 0xbe, 0xef]`. User is reponsible for the
|
||||
freeing of the returned byte array
|
||||
|
||||
```c
|
||||
|
12
src/crypto.c
12
src/crypto.c
@ -204,16 +204,22 @@ unsigned char *b64_decode(const char *s, size_t sz, size_t *decode_sz) {
|
||||
|
||||
unsigned char *hex_decode(const char *orig, size_t *sz) {
|
||||
size_t buf_sz = strlen(orig) + 1;
|
||||
char *sptr = orig;
|
||||
if (strncmp(orig, "0x", 2) == 0) {
|
||||
buf_sz -= 2;
|
||||
sptr += 2;
|
||||
}
|
||||
|
||||
if (strlen(orig) % 2 != 0) {
|
||||
buf_sz += 1;
|
||||
}
|
||||
|
||||
char *buf = malloc(sizeof(char) * buf_sz);
|
||||
if (strlen(orig) % 2 != 0) {
|
||||
strcpy(buf + 1, orig);
|
||||
if (strlen(sptr) % 2 != 0) {
|
||||
strcpy(buf+ 1, sptr);
|
||||
buf[0] = '0';
|
||||
} else {
|
||||
strcpy(buf, orig);
|
||||
strcpy(buf, sptr);
|
||||
}
|
||||
buf[buf_sz - 1] = '\0';
|
||||
|
||||
|
@ -349,6 +349,13 @@ void test_crypto() {
|
||||
}
|
||||
free(s);
|
||||
|
||||
// leading 0x
|
||||
s = hex_decode("0xf00f5", &s_sz);
|
||||
for (size_t i = 0; i < 3; ++i) {
|
||||
assert(s[i] == h2[i]);
|
||||
}
|
||||
free(s);
|
||||
|
||||
s = hex_encode(h, 4);
|
||||
assert(strcmp(s, "deadbeef") == 0);
|
||||
free(s);
|
||||
|
Loading…
x
Reference in New Issue
Block a user